llvm-6502/lib/CodeGen
Juergen Ributzka fb282c68b7 Add Constant Hoisting Pass
This pass identifies expensive constants to hoist and coalesces them to
better prepare it for SelectionDAG-based code generation. This works around the
limitations of the basic-block-at-a-time approach.

First it scans all instructions for integer constants and calculates its
cost. If the constant can be folded into the instruction (the cost is
TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
consider it expensive and leave it alone. This is the default behavior and
the default implementation of getIntImmCost will always return TCC_Free.

If the cost is more than TCC_BASIC, then the integer constant can't be folded
into the instruction and it might be beneficial to hoist the constant.
Similar constants are coalesced to reduce register pressure and
materialization code.

When a constant is hoisted, it is also hidden behind a bitcast to force it to
be live-out of the basic block. Otherwise the constant would be just
duplicated and each basic block would have its own copy in the SelectionDAG.
The SelectionDAG recognizes such constants as opaque and doesn't perform
certain transformations on them, which would create a new expensive constant.

This optimization is only applied to integer constants in instructions and
simple (this means not nested) constant cast experessions. For example:
%0 = load i64* inttoptr (i64 big_constant to i64*)

Reviewed by Eric

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@200022 91177308-0d34-0410-b5e6-96231b3b80d8
2014-01-24 18:23:08 +00:00
..
AsmPrinter Move emitInlineAsmEnd to the AsmPrinter interface. 2014-01-24 15:47:54 +00:00
SelectionDAG Add Constant Hoisting Pass 2014-01-24 18:23:08 +00:00
AggressiveAntiDepBreaker.cpp
AggressiveAntiDepBreaker.h
AllocationOrder.cpp
AllocationOrder.h Check hint registers for interference only once before evictions 2013-12-05 21:18:40 +00:00
Analysis.cpp
AntiDepBreaker.h
BasicTargetTransformInfo.cpp Add final and owerride keywords to TargetTransformInfo's subclasses. 2014-01-24 18:22:59 +00:00
BranchFolding.cpp Add a RequireStructuredCFG Field to TargetMachine. 2013-12-07 01:49:19 +00:00
BranchFolding.h
CalcSpillWeights.cpp [block-freq] Refactor LiveInterals::getSpillWeight to use the new MachineBlockFrequencyInfo methods. 2013-12-14 00:53:32 +00:00
CallingConvLower.cpp
CMakeLists.txt [Stackmap] Liveness Analysis Pass 2013-12-14 06:53:06 +00:00
CodeGen.cpp Re-sort all of the includes with ./utils/sort_includes.py so that 2014-01-07 11:48:04 +00:00
CriticalAntiDepBreaker.cpp Fix known typos 2014-01-24 17:20:08 +00:00
CriticalAntiDepBreaker.h
DeadMachineInstructionElim.cpp
DFAPacketizer.cpp
DwarfEHPrepare.cpp [PM] Split DominatorTree into a concrete analysis result object which 2014-01-13 13:07:17 +00:00
EarlyIfConversion.cpp
EdgeBundles.cpp
ErlangGC.cpp
ExecutionDepsFix.cpp Convert register liveness tracking to work on a sub-register level instead of just register units. 2013-12-14 06:52:56 +00:00
ExpandISelPseudos.cpp
ExpandPostRAPseudos.cpp fix typo in comment 2013-10-11 15:40:14 +00:00
GCMetadata.cpp
GCMetadataPrinter.cpp
GCStrategy.cpp [PM] Split DominatorTree into a concrete analysis result object which 2014-01-13 13:07:17 +00:00
IfConversion.cpp Re-sort all of the includes with ./utils/sort_includes.py so that 2014-01-07 11:48:04 +00:00
InlineSpiller.cpp Re-sort all of the includes with ./utils/sort_includes.py so that 2014-01-07 11:48:04 +00:00
InterferenceCache.cpp Represent RegUnit liveness with LiveRange instance 2013-10-10 21:29:02 +00:00
InterferenceCache.h Represent RegUnit liveness with LiveRange instance 2013-10-10 21:29:02 +00:00
IntrinsicLowering.cpp Use type form of getIntPtrType. 2013-11-10 04:46:57 +00:00
JITCodeEmitter.cpp
LatencyPriorityQueue.cpp
LexicalScopes.cpp Remove capability for polymorphic destruction from LexicalScope 2013-11-20 00:54:28 +00:00
LiveDebugVariables.cpp Remove capability for polymorphic destruction from LexicalScope 2013-11-20 00:54:28 +00:00
LiveDebugVariables.h
LiveInterval.cpp Print register in LiveInterval::print() 2013-10-10 21:29:05 +00:00
LiveIntervalAnalysis.cpp [block-freq] Rename getEntryFrequency() -> getEntryFreq() to match getBlockFreq() in all *BlockFrequencyInfo*. 2013-12-14 02:37:38 +00:00
LiveIntervalUnion.cpp
LivePhysRegs.cpp Convert register liveness tracking to work on a sub-register level instead of just register units. 2013-12-14 06:52:56 +00:00
LiveRangeCalc.cpp Work on LiveRange instead of LiveInterval where possible 2013-10-10 21:28:57 +00:00
LiveRangeCalc.h LiveRangeCalc.h: Update a description corresponding to r192396. [-Wdocumentation] 2013-10-11 04:52:03 +00:00
LiveRangeEdit.cpp CalcSpillWeights: give a better describing name to calculateSpillWeights 2013-11-11 19:04:45 +00:00
LiveRegMatrix.cpp Represent RegUnit liveness with LiveRange instance 2013-10-10 21:29:02 +00:00
LiveStackAnalysis.cpp
LiveVariables.cpp
LLVMBuild.txt Prune redundant dependencies in LLVMBuild.txt. 2013-12-11 00:30:57 +00:00
LLVMTargetMachine.cpp Simplify the logic for deciding when to initialize the sections. 2014-01-24 03:54:40 +00:00
LocalStackSlotAllocation.cpp [stackprotector] Use analysis from the StackProtector pass for stack layout in PEI a nd LocalStackSlot passes. 2013-12-19 03:17:11 +00:00
MachineBasicBlock.cpp Put the functionality for printing a value to a raw_ostream as an 2014-01-09 02:29:41 +00:00
MachineBlockFrequencyInfo.cpp [block-freq] Rename getEntryFrequency() -> getEntryFreq() to match getBlockFreq() in all *BlockFrequencyInfo*. 2013-12-14 02:37:38 +00:00
MachineBlockPlacement.cpp Add a LLVM_DUMP_METHOD macro. 2014-01-03 22:53:37 +00:00
MachineBranchProbabilityInfo.cpp
MachineCodeEmitter.cpp
MachineCopyPropagation.cpp MachineCopyPropagation has special logic for removing COPY instructions. It will remove plain COPYs using eraseFromParent(), but if the COPY has imp-defs/imp-uses it will convert it to a KILL, to keep the imp-def around. 2014-01-22 09:12:27 +00:00
MachineCSE.cpp Disabled subregister copy coalescing during MachineCSE. 2013-12-17 19:29:36 +00:00
MachineDominators.cpp
MachineFunction.cpp Put the functionality for printing a value to a raw_ostream as an 2014-01-09 02:29:41 +00:00
MachineFunctionAnalysis.cpp
MachineFunctionPass.cpp [stackprotector] Use analysis from the StackProtector pass for stack layout in PEI a nd LocalStackSlot passes. 2013-12-19 03:17:11 +00:00
MachineFunctionPrinterPass.cpp
MachineInstr.cpp Put the functionality for printing a value to a raw_ostream as an 2014-01-09 02:29:41 +00:00
MachineInstrBundle.cpp
MachineLICM.cpp Replace some unnecessary vector copies with references. 2013-09-15 22:04:42 +00:00
MachineLoopInfo.cpp
MachineModuleInfo.cpp
MachineModuleInfoImpls.cpp
MachinePassRegistry.cpp
MachinePostDominators.cpp
MachineRegisterInfo.cpp Re-sort all of the includes with ./utils/sort_includes.py so that 2014-01-07 11:48:04 +00:00
MachineScheduler.cpp Fix known typos 2014-01-24 17:20:08 +00:00
MachineSink.cpp MachineSink: Fix and tweak critical-edge breaking heuristic. 2013-10-14 16:57:17 +00:00
MachineSSAUpdater.cpp
MachineTraceMetrics.cpp
MachineVerifier.cpp Fix confusing machine verifier error. 2013-11-15 22:18:19 +00:00
Makefile
OcamlGC.cpp
OptimizePHIs.cpp
Passes.cpp Add Constant Hoisting Pass 2014-01-24 18:23:08 +00:00
PeepholeOptimizer.cpp
PHIElimination.cpp Fix typo 2014-01-22 02:38:23 +00:00
PHIEliminationUtils.cpp
PHIEliminationUtils.h
PostRASchedulerList.cpp Move the PostRA scheduler's fixupKills function for reuse. 2013-12-28 21:56:55 +00:00
ProcessImplicitDefs.cpp Fix typo 2013-10-04 16:52:58 +00:00
PrologEpilogInserter.cpp Re-sort all of the includes with ./utils/sort_includes.py so that 2014-01-07 11:48:04 +00:00
PrologEpilogInserter.h Remove the --shrink-wrap option. 2013-10-31 14:07:59 +00:00
PseudoSourceValue.cpp
README.txt
RegAllocBase.cpp DEBUG shouldEvict decisions 2013-11-22 19:07:42 +00:00
RegAllocBase.h [weak vtables] Remove a bunch of weak vtables 2013-11-19 00:57:56 +00:00
RegAllocBasic.cpp CalcSpillWeights: give a better describing name to calculateSpillWeights 2013-11-11 19:04:45 +00:00
RegAllocFast.cpp Explicitly request unsigned enum types when desired 2013-10-08 20:15:11 +00:00
RegAllocGreedy.cpp [RegAlloc] Make tryInstructionSplit less aggressive. 2014-01-02 22:47:22 +00:00
RegAllocPBQP.cpp [block-freq] Refactor LiveInterals::getSpillWeight to use the new MachineBlockFrequencyInfo methods. 2013-12-14 00:53:32 +00:00
RegisterClassInfo.cpp Make comment more explicit. 2013-12-17 02:18:02 +00:00
RegisterCoalescer.cpp ReMat: fix overly cavalier attitude to sub-register indices 2014-01-16 12:29:55 +00:00
RegisterCoalescer.h
RegisterPressure.cpp increase the accuracy of register pressure computation in the presence of dead definitions by using live intervals, if available, to identify dead definitions and proceed accordingly. 2013-11-08 22:46:28 +00:00
RegisterScavenging.cpp
ScheduleDAG.cpp Fix known typos 2014-01-24 17:20:08 +00:00
ScheduleDAGInstrs.cpp Track multiple stores per object when using AA in ScheduleDAGInstrs 2014-01-20 14:03:02 +00:00
ScheduleDAGPrinter.cpp Put the functionality for printing a value to a raw_ostream as an 2014-01-09 02:29:41 +00:00
ScoreboardHazardRecognizer.cpp
ShadowStackGC.cpp
SjLjEHPrepare.cpp CodeGen: Stop treating vectors as aggregates 2014-01-21 22:46:46 +00:00
SlotIndexes.cpp
Spiller.cpp Replacing HUGE_VALF with llvm::huge_valf in order to work around a warning triggered in MSVC 12. 2013-11-13 00:15:44 +00:00
Spiller.h
SpillPlacement.cpp [block-freq] Rename getEntryFrequency() -> getEntryFreq() to match getBlockFreq() in all *BlockFrequencyInfo*. 2013-12-14 02:37:38 +00:00
SpillPlacement.h [block-freq] Store MBFI as a field on SpillPlacement so we can access it to get the entry frequency while processing data. 2013-12-14 00:25:47 +00:00
SplitKit.cpp Work on LiveRange instead of LiveInterval where possible 2013-10-10 21:28:57 +00:00
SplitKit.h
StackColoring.cpp Update StackProtector when coloring merges stack slots 2014-01-20 19:49:14 +00:00
StackMapLivenessAnalysis.cpp [Stackmap] Liveness Analysis Pass 2013-12-14 06:53:06 +00:00
StackMaps.cpp Fix known typos 2014-01-24 17:20:08 +00:00
StackProtector.cpp Checked return warning from coverity 2014-01-21 10:24:35 +00:00
StackSlotColoring.cpp [block-freq] Refactor LiveInterals::getSpillWeight to use the new MachineBlockFrequencyInfo methods. 2013-12-14 00:53:32 +00:00
TailDuplication.cpp Remove several unused variables. 2013-10-01 13:32:03 +00:00
TargetFrameLoweringImpl.cpp
TargetInstrInfo.cpp Remove redundant fold call introduced in r195944. Thanks very much to Juergen 2014-01-02 19:38:41 +00:00
TargetLoweringBase.cpp Disable compare sinking in CodeGenPrepare when multiple condition registers are available 2014-01-02 21:13:43 +00:00
TargetLoweringObjectFileImpl.cpp Add a variable to track whether or not we've used a unique section, 2014-01-23 06:47:25 +00:00
TargetOptionsImpl.cpp Re-sort all of the includes with ./utils/sort_includes.py so that 2014-01-07 11:48:04 +00:00
TargetRegisterInfo.cpp
TargetSchedule.cpp IfConverter: Use TargetSchedule for instruction latencies 2013-09-30 15:28:56 +00:00
TwoAddressInstructionPass.cpp Allow MachineCSE to coalesce trivial subregister copies the same way that it coalesces normal copies. 2013-12-17 04:50:45 +00:00
UnreachableBlockElim.cpp [PM] Split DominatorTree into a concrete analysis result object which 2014-01-13 13:07:17 +00:00
VirtRegMap.cpp [VirtRegMap] Fix for PR17825. Do not ignore noreturn definitions when setting 2013-11-08 18:14:17 +00:00

//===---------------------------------------------------------------------===//

Common register allocation / spilling problem:

        mul lr, r4, lr
        str lr, [sp, #+52]
        ldr lr, [r1, #+32]
        sxth r3, r3
        ldr r4, [sp, #+52]
        mla r4, r3, lr, r4

can be:

        mul lr, r4, lr
        mov r4, lr
        str lr, [sp, #+52]
        ldr lr, [r1, #+32]
        sxth r3, r3
        mla r4, r3, lr, r4

and then "merge" mul and mov:

        mul r4, r4, lr
        str r4, [sp, #+52]
        ldr lr, [r1, #+32]
        sxth r3, r3
        mla r4, r3, lr, r4

It also increase the likelihood the store may become dead.

//===---------------------------------------------------------------------===//

bb27 ...
        ...
        %reg1037 = ADDri %reg1039, 1
        %reg1038 = ADDrs %reg1032, %reg1039, %NOREG, 10
    Successors according to CFG: 0x8b03bf0 (#5)

bb76 (0x8b03bf0, LLVM BB @0x8b032d0, ID#5):
    Predecessors according to CFG: 0x8b0c5f0 (#3) 0x8b0a7c0 (#4)
        %reg1039 = PHI %reg1070, mbb<bb76.outer,0x8b0c5f0>, %reg1037, mbb<bb27,0x8b0a7c0>

Note ADDri is not a two-address instruction. However, its result %reg1037 is an
operand of the PHI node in bb76 and its operand %reg1039 is the result of the
PHI node. We should treat it as a two-address code and make sure the ADDri is
scheduled after any node that reads %reg1039.

//===---------------------------------------------------------------------===//

Use local info (i.e. register scavenger) to assign it a free register to allow
reuse:
        ldr r3, [sp, #+4]
        add r3, r3, #3
        ldr r2, [sp, #+8]
        add r2, r2, #2
        ldr r1, [sp, #+4]  <==
        add r1, r1, #1
        ldr r0, [sp, #+4]
        add r0, r0, #2

//===---------------------------------------------------------------------===//

LLVM aggressively lift CSE out of loop. Sometimes this can be negative side-
effects:

R1 = X + 4
R2 = X + 7
R3 = X + 15

loop:
load [i + R1]
...
load [i + R2]
...
load [i + R3]

Suppose there is high register pressure, R1, R2, R3, can be spilled. We need
to implement proper re-materialization to handle this:

R1 = X + 4
R2 = X + 7
R3 = X + 15

loop:
R1 = X + 4  @ re-materialized
load [i + R1]
...
R2 = X + 7 @ re-materialized
load [i + R2]
...
R3 = X + 15 @ re-materialized
load [i + R3]

Furthermore, with re-association, we can enable sharing:

R1 = X + 4
R2 = X + 7
R3 = X + 15

loop:
T = i + X
load [T + 4]
...
load [T + 7]
...
load [T + 15]
//===---------------------------------------------------------------------===//

It's not always a good idea to choose rematerialization over spilling. If all
the load / store instructions would be folded then spilling is cheaper because
it won't require new live intervals / registers. See 2003-05-31-LongShifts for
an example.

//===---------------------------------------------------------------------===//

With a copying garbage collector, derived pointers must not be retained across
collector safe points; the collector could move the objects and invalidate the
derived pointer. This is bad enough in the first place, but safe points can
crop up unpredictably. Consider:

        %array = load { i32, [0 x %obj] }** %array_addr
        %nth_el = getelementptr { i32, [0 x %obj] }* %array, i32 0, i32 %n
        %old = load %obj** %nth_el
        %z = div i64 %x, %y
        store %obj* %new, %obj** %nth_el

If the i64 division is lowered to a libcall, then a safe point will (must)
appear for the call site. If a collection occurs, %array and %nth_el no longer
point into the correct object.

The fix for this is to copy address calculations so that dependent pointers
are never live across safe point boundaries. But the loads cannot be copied
like this if there was an intervening store, so may be hard to get right.

Only a concurrent mutator can trigger a collection at the libcall safe point.
So single-threaded programs do not have this requirement, even with a copying
collector. Still, LLVM optimizations would probably undo a front-end's careful
work.

//===---------------------------------------------------------------------===//

The ocaml frametable structure supports liveness information. It would be good
to support it.

//===---------------------------------------------------------------------===//

The FIXME in ComputeCommonTailLength in BranchFolding.cpp needs to be
revisited. The check is there to work around a misuse of directives in inline
assembly.

//===---------------------------------------------------------------------===//

It would be good to detect collector/target compatibility instead of silently
doing the wrong thing.

//===---------------------------------------------------------------------===//

It would be really nice to be able to write patterns in .td files for copies,
which would eliminate a bunch of explicit predicates on them (e.g. no side 
effects).  Once this is in place, it would be even better to have tblgen 
synthesize the various copy insertion/inspection methods in TargetInstrInfo.

//===---------------------------------------------------------------------===//

Stack coloring improvements:

1. Do proper LiveStackAnalysis on all stack objects including those which are
   not spill slots.
2. Reorder objects to fill in gaps between objects.
   e.g. 4, 1, <gap>, 4, 1, 1, 1, <gap>, 4 => 4, 1, 1, 1, 1, 4, 4

//===---------------------------------------------------------------------===//

The scheduler should be able to sort nearby instructions by their address. For
example, in an expanded memset sequence it's not uncommon to see code like this:

  movl $0, 4(%rdi)
  movl $0, 8(%rdi)
  movl $0, 12(%rdi)
  movl $0, 0(%rdi)

Each of the stores is independent, and the scheduler is currently making an
arbitrary decision about the order.

//===---------------------------------------------------------------------===//

Another opportunitiy in this code is that the $0 could be moved to a register:

  movl $0, 4(%rdi)
  movl $0, 8(%rdi)
  movl $0, 12(%rdi)
  movl $0, 0(%rdi)

This would save substantial code size, especially for longer sequences like
this. It would be easy to have a rule telling isel to avoid matching MOV32mi
if the immediate has more than some fixed number of uses. It's more involved
to teach the register allocator how to do late folding to recover from
excessive register pressure.