home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / documentation / documents / a252cmp < prev    next >
Internet Message Format  |  1999-04-27  |  2KB

  1. From: dseal@armltd.co.uk (David Seal)
  2. Subject: Doing comparisons correctly (was square roots)
  3. Date: 26 Nov 91 19:49:10 GMT
  4.  
  5. In article <1991Nov22.104626.8428@odin.diku.dk> torbenm@diku.dk (Torben
  6. AEgidius Mogensen) writes:
  7.  
  8. >Also, my ARM code used unsigned numbers but compared them as if they
  9. >were signed (using PL). Comparison of unsigned numbers requires HS.
  10.  
  11. Oops. Yes, comparison of unsigned numbers should use HS/HI/LS/LO (note HS
  12. and LO are other names for CS and CC, by the way). But comparison of signed
  13. numbers should use GE/GT/LE/LT, not PL or MI!!!
  14.  
  15. You should in general not use PL and MI after comparisons. They *can* be
  16. used after CMP Rn,#0, though GE and LT will do just as well. Comparing
  17. against any other value, PL and MI can produce misleading results. E.g.
  18. consider CMP Rn,#1. If Rn happens to contain the negative value &80000000,
  19. CMP Rn,#1 will set the condition flags according to the value &80000000-1 =
  20. &7FFFFFFF (giving a positive result - note there has been a signed overflow
  21. in this calculation). This means that it will clear the N flag, and code
  22. using PL/MI will decide that &80000000 >= 1 as a signed quantity! More
  23. generally, code using PL/MI will get the answer wrong whenever the implicit
  24. subtraction in the comparison suffers a signed overflow.
  25.  
  26. The GE/GT/LE/LT conditions take into account the possibility of signed
  27. overflow and so don't get the answer wrong when it happens.
  28.  
  29. When should you use PL/MI? Generally:
  30.  
  31.   (a) When you want to test the top bit of a value;
  32.  
  33.   (b) When you want to check the sign of a value without disturbing the C
  34.       flag, TEQ Rn,#0 followed by use of PL/MI does the trick;
  35.  
  36.   (c) The one exception I know to the above rule about not using PL/MI after
  37.       a comparison: if you're comparing two values of a steadily
  38.       incrementing clock, and you're reasonably confident that they aren't
  39.       more than 2^31-1 ticks apart, you should use PL/MI after a compare
  40.       instruction. This sort of "cyclic comparison" is rather peculiar - for
  41.       instance, you will find that &40000000 > 0, &80000000 > &40000000,
  42.       &C0000000 > &80000000 and 0 > &C0000000. The normal rule that if a > b
  43.       and b > c, then a > c does not apply to this type of comparison!
  44.  
  45.       This cyclic comparison should be used in programs manipulating
  46.       interval timer values, in order to make certain they don't go wrong
  47.       when the timer wraps round from positive to negative values.
  48.  
  49. David Seal
  50. dseal@armltd.co.uk
  51.