Add an include of SmallSet.h.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuild.cpp
1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/SelectionDAG.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetFrameInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/MathExtras.h"
49 #include <algorithm>
50 using namespace llvm;
51
52 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
53 /// insertvalue or extractvalue indices that identify a member, return
54 /// the linearized index of the start of the member.
55 ///
56 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
57                                    const unsigned *Indices,
58                                    const unsigned *IndicesEnd,
59                                    unsigned CurIndex = 0) {
60   // Base case: We're done.
61   if (Indices && Indices == IndicesEnd)
62     return CurIndex;
63
64   // Given a struct type, recursively traverse the elements.
65   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
66     for (StructType::element_iterator EB = STy->element_begin(),
67                                       EI = EB,
68                                       EE = STy->element_end();
69         EI != EE; ++EI) {
70       if (Indices && *Indices == unsigned(EI - EB))
71         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
72       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
73     }
74   }
75   // Given an array type, recursively traverse the elements.
76   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
77     const Type *EltTy = ATy->getElementType();
78     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
79       if (Indices && *Indices == i)
80         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
81       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
82     }
83   }
84   // We haven't found the type we're looking for, so keep searching.
85   return CurIndex + 1;
86 }
87
88 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
89 /// MVTs that represent all the individual underlying
90 /// non-aggregate types that comprise it.
91 ///
92 /// If Offsets is non-null, it points to a vector to be filled in
93 /// with the in-memory offsets of each of the individual values.
94 ///
95 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
96                             SmallVectorImpl<MVT> &ValueVTs,
97                             SmallVectorImpl<uint64_t> *Offsets = 0,
98                             uint64_t StartingOffset = 0) {
99   // Given a struct type, recursively traverse the elements.
100   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
101     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
102     for (StructType::element_iterator EB = STy->element_begin(),
103                                       EI = EB,
104                                       EE = STy->element_end();
105          EI != EE; ++EI)
106       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
107                       StartingOffset + SL->getElementOffset(EI - EB));
108     return;
109   }
110   // Given an array type, recursively traverse the elements.
111   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
112     const Type *EltTy = ATy->getElementType();
113     uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
114     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
115       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
116                       StartingOffset + i * EltSize);
117     return;
118   }
119   // Base case: we can get an MVT for this LLVM IR type.
120   ValueVTs.push_back(TLI.getValueType(Ty));
121   if (Offsets)
122     Offsets->push_back(StartingOffset);
123 }
124
125 namespace llvm {
126   /// RegsForValue - This struct represents the registers (physical or virtual)
127   /// that a particular set of values is assigned, and the type information about
128   /// the value. The most common situation is to represent one value at a time,
129   /// but struct or array values are handled element-wise as multiple values.
130   /// The splitting of aggregates is performed recursively, so that we never
131   /// have aggregate-typed registers. The values at this point do not necessarily
132   /// have legal types, so each value may require one or more registers of some
133   /// legal type.
134   /// 
135   struct VISIBILITY_HIDDEN RegsForValue {
136     /// TLI - The TargetLowering object.
137     ///
138     const TargetLowering *TLI;
139
140     /// ValueVTs - The value types of the values, which may not be legal, and
141     /// may need be promoted or synthesized from one or more registers.
142     ///
143     SmallVector<MVT, 4> ValueVTs;
144     
145     /// RegVTs - The value types of the registers. This is the same size as
146     /// ValueVTs and it records, for each value, what the type of the assigned
147     /// register or registers are. (Individual values are never synthesized
148     /// from more than one type of register.)
149     ///
150     /// With virtual registers, the contents of RegVTs is redundant with TLI's
151     /// getRegisterType member function, however when with physical registers
152     /// it is necessary to have a separate record of the types.
153     ///
154     SmallVector<MVT, 4> RegVTs;
155     
156     /// Regs - This list holds the registers assigned to the values.
157     /// Each legal or promoted value requires one register, and each
158     /// expanded value requires multiple registers.
159     ///
160     SmallVector<unsigned, 4> Regs;
161     
162     RegsForValue() : TLI(0) {}
163     
164     RegsForValue(const TargetLowering &tli,
165                  const SmallVector<unsigned, 4> &regs, 
166                  MVT regvt, MVT valuevt)
167       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
168     RegsForValue(const TargetLowering &tli,
169                  const SmallVector<unsigned, 4> &regs, 
170                  const SmallVector<MVT, 4> &regvts,
171                  const SmallVector<MVT, 4> &valuevts)
172       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
173     RegsForValue(const TargetLowering &tli,
174                  unsigned Reg, const Type *Ty) : TLI(&tli) {
175       ComputeValueVTs(tli, Ty, ValueVTs);
176
177       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
178         MVT ValueVT = ValueVTs[Value];
179         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
180         MVT RegisterVT = TLI->getRegisterType(ValueVT);
181         for (unsigned i = 0; i != NumRegs; ++i)
182           Regs.push_back(Reg + i);
183         RegVTs.push_back(RegisterVT);
184         Reg += NumRegs;
185       }
186     }
187     
188     /// append - Add the specified values to this one.
189     void append(const RegsForValue &RHS) {
190       TLI = RHS.TLI;
191       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
192       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
193       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
194     }
195     
196     
197     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
198     /// this value and returns the result as a ValueVTs value.  This uses 
199     /// Chain/Flag as the input and updates them for the output Chain/Flag.
200     /// If the Flag pointer is NULL, no flag is used.
201     SDValue getCopyFromRegs(SelectionDAG &DAG,
202                               SDValue &Chain, SDValue *Flag) const;
203
204     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
205     /// specified value into the registers specified by this object.  This uses 
206     /// Chain/Flag as the input and updates them for the output Chain/Flag.
207     /// If the Flag pointer is NULL, no flag is used.
208     void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
209                        SDValue &Chain, SDValue *Flag) const;
210     
211     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
212     /// operand list.  This adds the code marker and includes the number of 
213     /// values added into it.
214     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
215                               std::vector<SDValue> &Ops) const;
216   };
217 }
218
219 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
220 /// PHI nodes or outside of the basic block that defines it, or used by a 
221 /// switch or atomic instruction, which may expand to multiple basic blocks.
222 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
223   if (isa<PHINode>(I)) return true;
224   BasicBlock *BB = I->getParent();
225   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
226     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
227         // FIXME: Remove switchinst special case.
228         isa<SwitchInst>(*UI))
229       return true;
230   return false;
231 }
232
233 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
234 /// entry block, return true.  This includes arguments used by switches, since
235 /// the switch may expand into multiple basic blocks.
236 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
237   // With FastISel active, we may be splitting blocks, so force creation
238   // of virtual registers for all non-dead arguments.
239   if (EnableFastISel)
240     return A->use_empty();
241
242   BasicBlock *Entry = A->getParent()->begin();
243   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
244     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
245       return false;  // Use not in entry block.
246   return true;
247 }
248
249 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
250   : TLI(tli) {
251 }
252
253 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
254                                bool EnableFastISel) {
255   Fn = &fn;
256   MF = &mf;
257   RegInfo = &MF->getRegInfo();
258
259   // Create a vreg for each argument register that is not dead and is used
260   // outside of the entry block for the function.
261   for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
262        AI != E; ++AI)
263     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
264       InitializeRegForValue(AI);
265
266   // Initialize the mapping of values to registers.  This is only set up for
267   // instruction values that are used outside of the block that defines
268   // them.
269   Function::iterator BB = Fn->begin(), EB = Fn->end();
270   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
271     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
272       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
273         const Type *Ty = AI->getAllocatedType();
274         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
275         unsigned Align = 
276           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
277                    AI->getAlignment());
278
279         TySize *= CUI->getZExtValue();   // Get total allocated size.
280         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
281         StaticAllocaMap[AI] =
282           MF->getFrameInfo()->CreateStackObject(TySize, Align);
283       }
284
285   for (; BB != EB; ++BB)
286     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
287       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
288         if (!isa<AllocaInst>(I) ||
289             !StaticAllocaMap.count(cast<AllocaInst>(I)))
290           InitializeRegForValue(I);
291
292   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
293   // also creates the initial PHI MachineInstrs, though none of the input
294   // operands are populated.
295   for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
296     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
297     MBBMap[BB] = MBB;
298     MF->push_back(MBB);
299
300     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
301     // appropriate.
302     PHINode *PN;
303     for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
304       if (PN->use_empty()) continue;
305       
306       unsigned PHIReg = ValueMap[PN];
307       assert(PHIReg && "PHI node does not have an assigned virtual register!");
308
309       SmallVector<MVT, 4> ValueVTs;
310       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
311       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
312         MVT VT = ValueVTs[vti];
313         unsigned NumRegisters = TLI.getNumRegisters(VT);
314         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
315         for (unsigned i = 0; i != NumRegisters; ++i)
316           BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
317         PHIReg += NumRegisters;
318       }
319     }
320   }
321 }
322
323 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
324   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
325 }
326
327 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
328 /// the correctly promoted or expanded types.  Assign these registers
329 /// consecutive vreg numbers and return the first assigned number.
330 ///
331 /// In the case that the given value has struct or array type, this function
332 /// will assign registers for each member or element.
333 ///
334 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
335   SmallVector<MVT, 4> ValueVTs;
336   ComputeValueVTs(TLI, V->getType(), ValueVTs);
337
338   unsigned FirstReg = 0;
339   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
340     MVT ValueVT = ValueVTs[Value];
341     MVT RegisterVT = TLI.getRegisterType(ValueVT);
342
343     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
344     for (unsigned i = 0; i != NumRegs; ++i) {
345       unsigned R = MakeReg(RegisterVT);
346       if (!FirstReg) FirstReg = R;
347     }
348   }
349   return FirstReg;
350 }
351
352 /// getCopyFromParts - Create a value that contains the specified legal parts
353 /// combined into the value they represent.  If the parts combine to a type
354 /// larger then ValueVT then AssertOp can be used to specify whether the extra
355 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
356 /// (ISD::AssertSext).
357 static SDValue getCopyFromParts(SelectionDAG &DAG,
358                                   const SDValue *Parts,
359                                   unsigned NumParts,
360                                   MVT PartVT,
361                                   MVT ValueVT,
362                                   ISD::NodeType AssertOp = ISD::DELETED_NODE) {
363   assert(NumParts > 0 && "No parts to assemble!");
364   TargetLowering &TLI = DAG.getTargetLoweringInfo();
365   SDValue Val = Parts[0];
366
367   if (NumParts > 1) {
368     // Assemble the value from multiple parts.
369     if (!ValueVT.isVector()) {
370       unsigned PartBits = PartVT.getSizeInBits();
371       unsigned ValueBits = ValueVT.getSizeInBits();
372
373       // Assemble the power of 2 part.
374       unsigned RoundParts = NumParts & (NumParts - 1) ?
375         1 << Log2_32(NumParts) : NumParts;
376       unsigned RoundBits = PartBits * RoundParts;
377       MVT RoundVT = RoundBits == ValueBits ?
378         ValueVT : MVT::getIntegerVT(RoundBits);
379       SDValue Lo, Hi;
380
381       if (RoundParts > 2) {
382         MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
383         Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
384         Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
385                               PartVT, HalfVT);
386       } else {
387         Lo = Parts[0];
388         Hi = Parts[1];
389       }
390       if (TLI.isBigEndian())
391         std::swap(Lo, Hi);
392       Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
393
394       if (RoundParts < NumParts) {
395         // Assemble the trailing non-power-of-2 part.
396         unsigned OddParts = NumParts - RoundParts;
397         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
398         Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
399
400         // Combine the round and odd parts.
401         Lo = Val;
402         if (TLI.isBigEndian())
403           std::swap(Lo, Hi);
404         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
405         Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
406         Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
407                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
408                                          TLI.getShiftAmountTy()));
409         Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
410         Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
411       }
412     } else {
413       // Handle a multi-element vector.
414       MVT IntermediateVT, RegisterVT;
415       unsigned NumIntermediates;
416       unsigned NumRegs =
417         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
418                                    RegisterVT);
419       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
420       NumParts = NumRegs; // Silence a compiler warning.
421       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
422       assert(RegisterVT == Parts[0].getValueType() &&
423              "Part type doesn't match part!");
424
425       // Assemble the parts into intermediate operands.
426       SmallVector<SDValue, 8> Ops(NumIntermediates);
427       if (NumIntermediates == NumParts) {
428         // If the register was not expanded, truncate or copy the value,
429         // as appropriate.
430         for (unsigned i = 0; i != NumParts; ++i)
431           Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
432                                     PartVT, IntermediateVT);
433       } else if (NumParts > 0) {
434         // If the intermediate type was expanded, build the intermediate operands
435         // from the parts.
436         assert(NumParts % NumIntermediates == 0 &&
437                "Must expand into a divisible number of parts!");
438         unsigned Factor = NumParts / NumIntermediates;
439         for (unsigned i = 0; i != NumIntermediates; ++i)
440           Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
441                                     PartVT, IntermediateVT);
442       }
443
444       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
445       // operands.
446       Val = DAG.getNode(IntermediateVT.isVector() ?
447                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
448                         ValueVT, &Ops[0], NumIntermediates);
449     }
450   }
451
452   // There is now one part, held in Val.  Correct it to match ValueVT.
453   PartVT = Val.getValueType();
454
455   if (PartVT == ValueVT)
456     return Val;
457
458   if (PartVT.isVector()) {
459     assert(ValueVT.isVector() && "Unknown vector conversion!");
460     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
461   }
462
463   if (ValueVT.isVector()) {
464     assert(ValueVT.getVectorElementType() == PartVT &&
465            ValueVT.getVectorNumElements() == 1 &&
466            "Only trivial scalar-to-vector conversions should get here!");
467     return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
468   }
469
470   if (PartVT.isInteger() &&
471       ValueVT.isInteger()) {
472     if (ValueVT.bitsLT(PartVT)) {
473       // For a truncate, see if we have any information to
474       // indicate whether the truncated bits will always be
475       // zero or sign-extension.
476       if (AssertOp != ISD::DELETED_NODE)
477         Val = DAG.getNode(AssertOp, PartVT, Val,
478                           DAG.getValueType(ValueVT));
479       return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
480     } else {
481       return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
482     }
483   }
484
485   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
486     if (ValueVT.bitsLT(Val.getValueType()))
487       // FP_ROUND's are always exact here.
488       return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
489                          DAG.getIntPtrConstant(1));
490     return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
491   }
492
493   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
494     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
495
496   assert(0 && "Unknown mismatch!");
497   return SDValue();
498 }
499
500 /// getCopyToParts - Create a series of nodes that contain the specified value
501 /// split into legal parts.  If the parts contain more bits than Val, then, for
502 /// integers, ExtendKind can be used to specify how to generate the extra bits.
503 static void getCopyToParts(SelectionDAG &DAG,
504                            SDValue Val,
505                            SDValue *Parts,
506                            unsigned NumParts,
507                            MVT PartVT,
508                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
509   TargetLowering &TLI = DAG.getTargetLoweringInfo();
510   MVT PtrVT = TLI.getPointerTy();
511   MVT ValueVT = Val.getValueType();
512   unsigned PartBits = PartVT.getSizeInBits();
513   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
514
515   if (!NumParts)
516     return;
517
518   if (!ValueVT.isVector()) {
519     if (PartVT == ValueVT) {
520       assert(NumParts == 1 && "No-op copy with multiple parts!");
521       Parts[0] = Val;
522       return;
523     }
524
525     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
526       // If the parts cover more bits than the value has, promote the value.
527       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
528         assert(NumParts == 1 && "Do not know what to promote to!");
529         Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
530       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
531         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
532         Val = DAG.getNode(ExtendKind, ValueVT, Val);
533       } else {
534         assert(0 && "Unknown mismatch!");
535       }
536     } else if (PartBits == ValueVT.getSizeInBits()) {
537       // Different types of the same size.
538       assert(NumParts == 1 && PartVT != ValueVT);
539       Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
540     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
541       // If the parts cover less bits than value has, truncate the value.
542       if (PartVT.isInteger() && ValueVT.isInteger()) {
543         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
544         Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
545       } else {
546         assert(0 && "Unknown mismatch!");
547       }
548     }
549
550     // The value may have changed - recompute ValueVT.
551     ValueVT = Val.getValueType();
552     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
553            "Failed to tile the value with PartVT!");
554
555     if (NumParts == 1) {
556       assert(PartVT == ValueVT && "Type conversion failed!");
557       Parts[0] = Val;
558       return;
559     }
560
561     // Expand the value into multiple parts.
562     if (NumParts & (NumParts - 1)) {
563       // The number of parts is not a power of 2.  Split off and copy the tail.
564       assert(PartVT.isInteger() && ValueVT.isInteger() &&
565              "Do not know what to expand to!");
566       unsigned RoundParts = 1 << Log2_32(NumParts);
567       unsigned RoundBits = RoundParts * PartBits;
568       unsigned OddParts = NumParts - RoundParts;
569       SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
570                                      DAG.getConstant(RoundBits,
571                                                      TLI.getShiftAmountTy()));
572       getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
573       if (TLI.isBigEndian())
574         // The odd parts were reversed by getCopyToParts - unreverse them.
575         std::reverse(Parts + RoundParts, Parts + NumParts);
576       NumParts = RoundParts;
577       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
578       Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
579     }
580
581     // The number of parts is a power of 2.  Repeatedly bisect the value using
582     // EXTRACT_ELEMENT.
583     Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
584                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
585                            Val);
586     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
587       for (unsigned i = 0; i < NumParts; i += StepSize) {
588         unsigned ThisBits = StepSize * PartBits / 2;
589         MVT ThisVT = MVT::getIntegerVT (ThisBits);
590         SDValue &Part0 = Parts[i];
591         SDValue &Part1 = Parts[i+StepSize/2];
592
593         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
594                             DAG.getConstant(1, PtrVT));
595         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
596                             DAG.getConstant(0, PtrVT));
597
598         if (ThisBits == PartBits && ThisVT != PartVT) {
599           Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
600           Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
601         }
602       }
603     }
604
605     if (TLI.isBigEndian())
606       std::reverse(Parts, Parts + NumParts);
607
608     return;
609   }
610
611   // Vector ValueVT.
612   if (NumParts == 1) {
613     if (PartVT != ValueVT) {
614       if (PartVT.isVector()) {
615         Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
616       } else {
617         assert(ValueVT.getVectorElementType() == PartVT &&
618                ValueVT.getVectorNumElements() == 1 &&
619                "Only trivial vector-to-scalar conversions should get here!");
620         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
621                           DAG.getConstant(0, PtrVT));
622       }
623     }
624
625     Parts[0] = Val;
626     return;
627   }
628
629   // Handle a multi-element vector.
630   MVT IntermediateVT, RegisterVT;
631   unsigned NumIntermediates;
632   unsigned NumRegs =
633     DAG.getTargetLoweringInfo()
634       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
635                               RegisterVT);
636   unsigned NumElements = ValueVT.getVectorNumElements();
637
638   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
639   NumParts = NumRegs; // Silence a compiler warning.
640   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
641
642   // Split the vector into intermediate operands.
643   SmallVector<SDValue, 8> Ops(NumIntermediates);
644   for (unsigned i = 0; i != NumIntermediates; ++i)
645     if (IntermediateVT.isVector())
646       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
647                            IntermediateVT, Val,
648                            DAG.getConstant(i * (NumElements / NumIntermediates),
649                                            PtrVT));
650     else
651       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
652                            IntermediateVT, Val, 
653                            DAG.getConstant(i, PtrVT));
654
655   // Split the intermediate operands into legal parts.
656   if (NumParts == NumIntermediates) {
657     // If the register was not expanded, promote or copy the value,
658     // as appropriate.
659     for (unsigned i = 0; i != NumParts; ++i)
660       getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
661   } else if (NumParts > 0) {
662     // If the intermediate type was expanded, split each the value into
663     // legal parts.
664     assert(NumParts % NumIntermediates == 0 &&
665            "Must expand into a divisible number of parts!");
666     unsigned Factor = NumParts / NumIntermediates;
667     for (unsigned i = 0; i != NumIntermediates; ++i)
668       getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
669   }
670 }
671
672
673 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
674   AA = &aa;
675   GFI = gfi;
676   TD = DAG.getTarget().getTargetData();
677 }
678
679 /// clear - Clear out the curret SelectionDAG and the associated
680 /// state and prepare this SelectionDAGLowering object to be used
681 /// for a new block. This doesn't clear out information about
682 /// additional blocks that are needed to complete switch lowering
683 /// or PHI node updating; that information is cleared out as it is
684 /// consumed.
685 void SelectionDAGLowering::clear() {
686   NodeMap.clear();
687   PendingLoads.clear();
688   PendingExports.clear();
689   DAG.clear();
690 }
691
692 /// getRoot - Return the current virtual root of the Selection DAG,
693 /// flushing any PendingLoad items. This must be done before emitting
694 /// a store or any other node that may need to be ordered after any
695 /// prior load instructions.
696 ///
697 SDValue SelectionDAGLowering::getRoot() {
698   if (PendingLoads.empty())
699     return DAG.getRoot();
700
701   if (PendingLoads.size() == 1) {
702     SDValue Root = PendingLoads[0];
703     DAG.setRoot(Root);
704     PendingLoads.clear();
705     return Root;
706   }
707
708   // Otherwise, we have to make a token factor node.
709   SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
710                                &PendingLoads[0], PendingLoads.size());
711   PendingLoads.clear();
712   DAG.setRoot(Root);
713   return Root;
714 }
715
716 /// getControlRoot - Similar to getRoot, but instead of flushing all the
717 /// PendingLoad items, flush all the PendingExports items. It is necessary
718 /// to do this before emitting a terminator instruction.
719 ///
720 SDValue SelectionDAGLowering::getControlRoot() {
721   SDValue Root = DAG.getRoot();
722
723   if (PendingExports.empty())
724     return Root;
725
726   // Turn all of the CopyToReg chains into one factored node.
727   if (Root.getOpcode() != ISD::EntryToken) {
728     unsigned i = 0, e = PendingExports.size();
729     for (; i != e; ++i) {
730       assert(PendingExports[i].getNode()->getNumOperands() > 1);
731       if (PendingExports[i].getNode()->getOperand(0) == Root)
732         break;  // Don't add the root if we already indirectly depend on it.
733     }
734
735     if (i == e)
736       PendingExports.push_back(Root);
737   }
738
739   Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
740                      &PendingExports[0],
741                      PendingExports.size());
742   PendingExports.clear();
743   DAG.setRoot(Root);
744   return Root;
745 }
746
747 void SelectionDAGLowering::visit(Instruction &I) {
748   visit(I.getOpcode(), I);
749 }
750
751 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
752   // Note: this doesn't use InstVisitor, because it has to work with
753   // ConstantExpr's in addition to instructions.
754   switch (Opcode) {
755   default: assert(0 && "Unknown instruction type encountered!");
756            abort();
757     // Build the switch statement using the Instruction.def file.
758 #define HANDLE_INST(NUM, OPCODE, CLASS) \
759   case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
760 #include "llvm/Instruction.def"
761   }
762
763
764 void SelectionDAGLowering::visitAdd(User &I) {
765   if (I.getType()->isFPOrFPVector())
766     visitBinary(I, ISD::FADD);
767   else
768     visitBinary(I, ISD::ADD);
769 }
770
771 void SelectionDAGLowering::visitMul(User &I) {
772   if (I.getType()->isFPOrFPVector())
773     visitBinary(I, ISD::FMUL);
774   else
775     visitBinary(I, ISD::MUL);
776 }
777
778 SDValue SelectionDAGLowering::getValue(const Value *V) {
779   SDValue &N = NodeMap[V];
780   if (N.getNode()) return N;
781   
782   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
783     MVT VT = TLI.getValueType(V->getType(), true);
784     
785     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
786       return N = DAG.getConstant(CI->getValue(), VT);
787
788     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
789       return N = DAG.getGlobalAddress(GV, VT);
790     
791     if (isa<ConstantPointerNull>(C))
792       return N = DAG.getConstant(0, TLI.getPointerTy());
793     
794     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
795       return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
796     
797     if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
798         !V->getType()->isAggregateType())
799       return N = DAG.getNode(ISD::UNDEF, VT);
800
801     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
802       visit(CE->getOpcode(), *CE);
803       SDValue N1 = NodeMap[V];
804       assert(N1.getNode() && "visit didn't populate the ValueMap!");
805       return N1;
806     }
807     
808     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
809       SmallVector<SDValue, 4> Constants;
810       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
811            OI != OE; ++OI) {
812         SDNode *Val = getValue(*OI).getNode();
813         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
814           Constants.push_back(SDValue(Val, i));
815       }
816       return DAG.getMergeValues(&Constants[0], Constants.size());
817     }
818
819     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
820       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
821              "Unknown struct or array constant!");
822
823       SmallVector<MVT, 4> ValueVTs;
824       ComputeValueVTs(TLI, C->getType(), ValueVTs);
825       unsigned NumElts = ValueVTs.size();
826       if (NumElts == 0)
827         return SDValue(); // empty struct
828       SmallVector<SDValue, 4> Constants(NumElts);
829       for (unsigned i = 0; i != NumElts; ++i) {
830         MVT EltVT = ValueVTs[i];
831         if (isa<UndefValue>(C))
832           Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
833         else if (EltVT.isFloatingPoint())
834           Constants[i] = DAG.getConstantFP(0, EltVT);
835         else
836           Constants[i] = DAG.getConstant(0, EltVT);
837       }
838       return DAG.getMergeValues(&Constants[0], NumElts);
839     }
840
841     const VectorType *VecTy = cast<VectorType>(V->getType());
842     unsigned NumElements = VecTy->getNumElements();
843     
844     // Now that we know the number and type of the elements, get that number of
845     // elements into the Ops array based on what kind of constant it is.
846     SmallVector<SDValue, 16> Ops;
847     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
848       for (unsigned i = 0; i != NumElements; ++i)
849         Ops.push_back(getValue(CP->getOperand(i)));
850     } else {
851       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
852              "Unknown vector constant!");
853       MVT EltVT = TLI.getValueType(VecTy->getElementType());
854
855       SDValue Op;
856       if (isa<UndefValue>(C))
857         Op = DAG.getNode(ISD::UNDEF, EltVT);
858       else if (EltVT.isFloatingPoint())
859         Op = DAG.getConstantFP(0, EltVT);
860       else
861         Op = DAG.getConstant(0, EltVT);
862       Ops.assign(NumElements, Op);
863     }
864     
865     // Create a BUILD_VECTOR node.
866     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
867   }
868       
869   // If this is a static alloca, generate it as the frameindex instead of
870   // computation.
871   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
872     DenseMap<const AllocaInst*, int>::iterator SI =
873       FuncInfo.StaticAllocaMap.find(AI);
874     if (SI != FuncInfo.StaticAllocaMap.end())
875       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
876   }
877       
878   unsigned InReg = FuncInfo.ValueMap[V];
879   assert(InReg && "Value not in map!");
880   
881   RegsForValue RFV(TLI, InReg, V->getType());
882   SDValue Chain = DAG.getEntryNode();
883   return RFV.getCopyFromRegs(DAG, Chain, NULL);
884 }
885
886
887 void SelectionDAGLowering::visitRet(ReturnInst &I) {
888   if (I.getNumOperands() == 0) {
889     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
890     return;
891   }
892   
893   SmallVector<SDValue, 8> NewValues;
894   NewValues.push_back(getControlRoot());
895   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {  
896     SDValue RetOp = getValue(I.getOperand(i));
897
898     SmallVector<MVT, 4> ValueVTs;
899     ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
900     for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
901       MVT VT = ValueVTs[j];
902
903       // FIXME: C calling convention requires the return type to be promoted to
904       // at least 32-bit. But this is not necessary for non-C calling conventions.
905       if (VT.isInteger()) {
906         MVT MinVT = TLI.getRegisterType(MVT::i32);
907         if (VT.bitsLT(MinVT))
908           VT = MinVT;
909       }
910
911       unsigned NumParts = TLI.getNumRegisters(VT);
912       MVT PartVT = TLI.getRegisterType(VT);
913       SmallVector<SDValue, 4> Parts(NumParts);
914       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
915   
916       const Function *F = I.getParent()->getParent();
917       if (F->paramHasAttr(0, ParamAttr::SExt))
918         ExtendKind = ISD::SIGN_EXTEND;
919       else if (F->paramHasAttr(0, ParamAttr::ZExt))
920         ExtendKind = ISD::ZERO_EXTEND;
921
922       getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
923                      &Parts[0], NumParts, PartVT, ExtendKind);
924
925       for (unsigned i = 0; i < NumParts; ++i) {
926         NewValues.push_back(Parts[i]);
927         NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
928       }
929     }
930   }
931   DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
932                           &NewValues[0], NewValues.size()));
933 }
934
935 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
936 /// the current basic block, add it to ValueMap now so that we'll get a
937 /// CopyTo/FromReg.
938 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
939   // No need to export constants.
940   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
941   
942   // Already exported?
943   if (FuncInfo.isExportedInst(V)) return;
944
945   unsigned Reg = FuncInfo.InitializeRegForValue(V);
946   CopyValueToVirtualRegister(V, Reg);
947 }
948
949 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
950                                                     const BasicBlock *FromBB) {
951   // The operands of the setcc have to be in this block.  We don't know
952   // how to export them from some other block.
953   if (Instruction *VI = dyn_cast<Instruction>(V)) {
954     // Can export from current BB.
955     if (VI->getParent() == FromBB)
956       return true;
957     
958     // Is already exported, noop.
959     return FuncInfo.isExportedInst(V);
960   }
961   
962   // If this is an argument, we can export it if the BB is the entry block or
963   // if it is already exported.
964   if (isa<Argument>(V)) {
965     if (FromBB == &FromBB->getParent()->getEntryBlock())
966       return true;
967
968     // Otherwise, can only export this if it is already exported.
969     return FuncInfo.isExportedInst(V);
970   }
971   
972   // Otherwise, constants can always be exported.
973   return true;
974 }
975
976 static bool InBlock(const Value *V, const BasicBlock *BB) {
977   if (const Instruction *I = dyn_cast<Instruction>(V))
978     return I->getParent() == BB;
979   return true;
980 }
981
982 /// FindMergedConditions - If Cond is an expression like 
983 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
984                                                 MachineBasicBlock *TBB,
985                                                 MachineBasicBlock *FBB,
986                                                 MachineBasicBlock *CurBB,
987                                                 unsigned Opc) {
988   // If this node is not part of the or/and tree, emit it as a branch.
989   Instruction *BOp = dyn_cast<Instruction>(Cond);
990
991   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 
992       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
993       BOp->getParent() != CurBB->getBasicBlock() ||
994       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
995       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
996     const BasicBlock *BB = CurBB->getBasicBlock();
997     
998     // If the leaf of the tree is a comparison, merge the condition into 
999     // the caseblock.
1000     if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1001         // The operands of the cmp have to be in this block.  We don't know
1002         // how to export them from some other block.  If this is the first block
1003         // of the sequence, no exporting is needed.
1004         (CurBB == CurMBB ||
1005          (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1006           isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1007       BOp = cast<Instruction>(Cond);
1008       ISD::CondCode Condition;
1009       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1010         switch (IC->getPredicate()) {
1011         default: assert(0 && "Unknown icmp predicate opcode!");
1012         case ICmpInst::ICMP_EQ:  Condition = ISD::SETEQ;  break;
1013         case ICmpInst::ICMP_NE:  Condition = ISD::SETNE;  break;
1014         case ICmpInst::ICMP_SLE: Condition = ISD::SETLE;  break;
1015         case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1016         case ICmpInst::ICMP_SGE: Condition = ISD::SETGE;  break;
1017         case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1018         case ICmpInst::ICMP_SLT: Condition = ISD::SETLT;  break;
1019         case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1020         case ICmpInst::ICMP_SGT: Condition = ISD::SETGT;  break;
1021         case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1022         }
1023       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1024         ISD::CondCode FPC, FOC;
1025         switch (FC->getPredicate()) {
1026         default: assert(0 && "Unknown fcmp predicate opcode!");
1027         case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1028         case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1029         case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1030         case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1031         case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1032         case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1033         case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1034         case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1035         case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1036         case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1037         case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1038         case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1039         case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1040         case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1041         case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1042         case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1043         }
1044         if (FiniteOnlyFPMath())
1045           Condition = FOC;
1046         else 
1047           Condition = FPC;
1048       } else {
1049         Condition = ISD::SETEQ; // silence warning.
1050         assert(0 && "Unknown compare instruction");
1051       }
1052       
1053       CaseBlock CB(Condition, BOp->getOperand(0), 
1054                    BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1055       SwitchCases.push_back(CB);
1056       return;
1057     }
1058     
1059     // Create a CaseBlock record representing this branch.
1060     CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1061                  NULL, TBB, FBB, CurBB);
1062     SwitchCases.push_back(CB);
1063     return;
1064   }
1065   
1066   
1067   //  Create TmpBB after CurBB.
1068   MachineFunction::iterator BBI = CurBB;
1069   MachineFunction &MF = DAG.getMachineFunction();
1070   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1071   CurBB->getParent()->insert(++BBI, TmpBB);
1072   
1073   if (Opc == Instruction::Or) {
1074     // Codegen X | Y as:
1075     //   jmp_if_X TBB
1076     //   jmp TmpBB
1077     // TmpBB:
1078     //   jmp_if_Y TBB
1079     //   jmp FBB
1080     //
1081   
1082     // Emit the LHS condition.
1083     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1084   
1085     // Emit the RHS condition into TmpBB.
1086     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1087   } else {
1088     assert(Opc == Instruction::And && "Unknown merge op!");
1089     // Codegen X & Y as:
1090     //   jmp_if_X TmpBB
1091     //   jmp FBB
1092     // TmpBB:
1093     //   jmp_if_Y TBB
1094     //   jmp FBB
1095     //
1096     //  This requires creation of TmpBB after CurBB.
1097     
1098     // Emit the LHS condition.
1099     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1100     
1101     // Emit the RHS condition into TmpBB.
1102     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1103   }
1104 }
1105
1106 /// If the set of cases should be emitted as a series of branches, return true.
1107 /// If we should emit this as a bunch of and/or'd together conditions, return
1108 /// false.
1109 bool 
1110 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1111   if (Cases.size() != 2) return true;
1112   
1113   // If this is two comparisons of the same values or'd or and'd together, they
1114   // will get folded into a single comparison, so don't emit two blocks.
1115   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1116        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1117       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1118        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1119     return false;
1120   }
1121   
1122   return true;
1123 }
1124
1125 void SelectionDAGLowering::visitBr(BranchInst &I) {
1126   // Update machine-CFG edges.
1127   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1128
1129   // Figure out which block is immediately after the current one.
1130   MachineBasicBlock *NextBlock = 0;
1131   MachineFunction::iterator BBI = CurMBB;
1132   if (++BBI != CurMBB->getParent()->end())
1133     NextBlock = BBI;
1134
1135   if (I.isUnconditional()) {
1136     // Update machine-CFG edges.
1137     CurMBB->addSuccessor(Succ0MBB);
1138     
1139     // If this is not a fall-through branch, emit the branch.
1140     if (Succ0MBB != NextBlock)
1141       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1142                               DAG.getBasicBlock(Succ0MBB)));
1143     return;
1144   }
1145
1146   // If this condition is one of the special cases we handle, do special stuff
1147   // now.
1148   Value *CondVal = I.getCondition();
1149   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1150
1151   // If this is a series of conditions that are or'd or and'd together, emit
1152   // this as a sequence of branches instead of setcc's with and/or operations.
1153   // For example, instead of something like:
1154   //     cmp A, B
1155   //     C = seteq 
1156   //     cmp D, E
1157   //     F = setle 
1158   //     or C, F
1159   //     jnz foo
1160   // Emit:
1161   //     cmp A, B
1162   //     je foo
1163   //     cmp D, E
1164   //     jle foo
1165   //
1166   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1167     if (BOp->hasOneUse() && 
1168         (BOp->getOpcode() == Instruction::And ||
1169          BOp->getOpcode() == Instruction::Or)) {
1170       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1171       // If the compares in later blocks need to use values not currently
1172       // exported from this block, export them now.  This block should always
1173       // be the first entry.
1174       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1175       
1176       // Allow some cases to be rejected.
1177       if (ShouldEmitAsBranches(SwitchCases)) {
1178         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1179           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1180           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1181         }
1182         
1183         // Emit the branch for this block.
1184         visitSwitchCase(SwitchCases[0]);
1185         SwitchCases.erase(SwitchCases.begin());
1186         return;
1187       }
1188       
1189       // Okay, we decided not to do this, remove any inserted MBB's and clear
1190       // SwitchCases.
1191       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1192         CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1193       
1194       SwitchCases.clear();
1195     }
1196   }
1197   
1198   // Create a CaseBlock record representing this branch.
1199   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1200                NULL, Succ0MBB, Succ1MBB, CurMBB);
1201   // Use visitSwitchCase to actually insert the fast branch sequence for this
1202   // cond branch.
1203   visitSwitchCase(CB);
1204 }
1205
1206 /// visitSwitchCase - Emits the necessary code to represent a single node in
1207 /// the binary search tree resulting from lowering a switch instruction.
1208 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1209   SDValue Cond;
1210   SDValue CondLHS = getValue(CB.CmpLHS);
1211   
1212   // Build the setcc now. 
1213   if (CB.CmpMHS == NULL) {
1214     // Fold "(X == true)" to X and "(X == false)" to !X to
1215     // handle common cases produced by branch lowering.
1216     if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1217       Cond = CondLHS;
1218     else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1219       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1220       Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1221     } else
1222       Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1223   } else {
1224     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1225
1226     uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1227     uint64_t High  = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1228
1229     SDValue CmpOp = getValue(CB.CmpMHS);
1230     MVT VT = CmpOp.getValueType();
1231
1232     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1233       Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1234     } else {
1235       SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1236       Cond = DAG.getSetCC(MVT::i1, SUB,
1237                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1238     }
1239   }
1240   
1241   // Update successor info
1242   CurMBB->addSuccessor(CB.TrueBB);
1243   CurMBB->addSuccessor(CB.FalseBB);
1244   
1245   // Set NextBlock to be the MBB immediately after the current one, if any.
1246   // This is used to avoid emitting unnecessary branches to the next block.
1247   MachineBasicBlock *NextBlock = 0;
1248   MachineFunction::iterator BBI = CurMBB;
1249   if (++BBI != CurMBB->getParent()->end())
1250     NextBlock = BBI;
1251   
1252   // If the lhs block is the next block, invert the condition so that we can
1253   // fall through to the lhs instead of the rhs block.
1254   if (CB.TrueBB == NextBlock) {
1255     std::swap(CB.TrueBB, CB.FalseBB);
1256     SDValue True = DAG.getConstant(1, Cond.getValueType());
1257     Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1258   }
1259   SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1260                                  DAG.getBasicBlock(CB.TrueBB));
1261   
1262   // If the branch was constant folded, fix up the CFG.
1263   if (BrCond.getOpcode() == ISD::BR) {
1264     CurMBB->removeSuccessor(CB.FalseBB);
1265     DAG.setRoot(BrCond);
1266   } else {
1267     // Otherwise, go ahead and insert the false branch.
1268     if (BrCond == getControlRoot()) 
1269       CurMBB->removeSuccessor(CB.TrueBB);
1270     
1271     if (CB.FalseBB == NextBlock)
1272       DAG.setRoot(BrCond);
1273     else
1274       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1275                               DAG.getBasicBlock(CB.FalseBB)));
1276   }
1277 }
1278
1279 /// visitJumpTable - Emit JumpTable node in the current MBB
1280 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1281   // Emit the code for the jump table
1282   assert(JT.Reg != -1U && "Should lower JT Header first!");
1283   MVT PTy = TLI.getPointerTy();
1284   SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1285   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1286   DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1287                           Table, Index));
1288   return;
1289 }
1290
1291 /// visitJumpTableHeader - This function emits necessary code to produce index
1292 /// in the JumpTable from switch case.
1293 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1294                                                 JumpTableHeader &JTH) {
1295   // Subtract the lowest switch case value from the value being switched on
1296   // and conditional branch to default mbb if the result is greater than the
1297   // difference between smallest and largest cases.
1298   SDValue SwitchOp = getValue(JTH.SValue);
1299   MVT VT = SwitchOp.getValueType();
1300   SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1301                               DAG.getConstant(JTH.First, VT));
1302   
1303   // The SDNode we just created, which holds the value being switched on
1304   // minus the the smallest case value, needs to be copied to a virtual
1305   // register so it can be used as an index into the jump table in a 
1306   // subsequent basic block.  This value may be smaller or larger than the
1307   // target's pointer type, and therefore require extension or truncating.
1308   if (VT.bitsGT(TLI.getPointerTy()))
1309     SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1310   else
1311     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1312   
1313   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1314   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1315   JT.Reg = JumpTableReg;
1316
1317   // Emit the range check for the jump table, and branch to the default
1318   // block for the switch statement if the value being switched on exceeds
1319   // the largest case in the switch.
1320   SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1321                                DAG.getConstant(JTH.Last-JTH.First,VT),
1322                                ISD::SETUGT);
1323
1324   // Set NextBlock to be the MBB immediately after the current one, if any.
1325   // This is used to avoid emitting unnecessary branches to the next block.
1326   MachineBasicBlock *NextBlock = 0;
1327   MachineFunction::iterator BBI = CurMBB;
1328   if (++BBI != CurMBB->getParent()->end())
1329     NextBlock = BBI;
1330
1331   SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1332                                  DAG.getBasicBlock(JT.Default));
1333
1334   if (JT.MBB == NextBlock)
1335     DAG.setRoot(BrCond);
1336   else
1337     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1338                             DAG.getBasicBlock(JT.MBB)));
1339
1340   return;
1341 }
1342
1343 /// visitBitTestHeader - This function emits necessary code to produce value
1344 /// suitable for "bit tests"
1345 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1346   // Subtract the minimum value
1347   SDValue SwitchOp = getValue(B.SValue);
1348   MVT VT = SwitchOp.getValueType();
1349   SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1350                               DAG.getConstant(B.First, VT));
1351
1352   // Check range
1353   SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1354                                     DAG.getConstant(B.Range, VT),
1355                                     ISD::SETUGT);
1356
1357   SDValue ShiftOp;
1358   if (VT.bitsGT(TLI.getShiftAmountTy()))
1359     ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1360   else
1361     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1362
1363   // Make desired shift
1364   SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1365                                     DAG.getConstant(1, TLI.getPointerTy()),
1366                                     ShiftOp);
1367
1368   unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1369   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1370   B.Reg = SwitchReg;
1371
1372   // Set NextBlock to be the MBB immediately after the current one, if any.
1373   // This is used to avoid emitting unnecessary branches to the next block.
1374   MachineBasicBlock *NextBlock = 0;
1375   MachineFunction::iterator BBI = CurMBB;
1376   if (++BBI != CurMBB->getParent()->end())
1377     NextBlock = BBI;
1378
1379   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1380
1381   CurMBB->addSuccessor(B.Default);
1382   CurMBB->addSuccessor(MBB);
1383
1384   SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1385                                   DAG.getBasicBlock(B.Default));
1386   
1387   if (MBB == NextBlock)
1388     DAG.setRoot(BrRange);
1389   else
1390     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1391                             DAG.getBasicBlock(MBB)));
1392
1393   return;
1394 }
1395
1396 /// visitBitTestCase - this function produces one "bit test"
1397 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1398                                             unsigned Reg,
1399                                             BitTestCase &B) {
1400   // Emit bit tests and jumps
1401   SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, 
1402                                            TLI.getPointerTy());
1403   
1404   SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1405                                 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1406   SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1407                                   DAG.getConstant(0, TLI.getPointerTy()),
1408                                   ISD::SETNE);
1409
1410   CurMBB->addSuccessor(B.TargetBB);
1411   CurMBB->addSuccessor(NextMBB);
1412   
1413   SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1414                                 AndCmp, DAG.getBasicBlock(B.TargetBB));
1415
1416   // Set NextBlock to be the MBB immediately after the current one, if any.
1417   // This is used to avoid emitting unnecessary branches to the next block.
1418   MachineBasicBlock *NextBlock = 0;
1419   MachineFunction::iterator BBI = CurMBB;
1420   if (++BBI != CurMBB->getParent()->end())
1421     NextBlock = BBI;
1422
1423   if (NextMBB == NextBlock)
1424     DAG.setRoot(BrAnd);
1425   else
1426     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1427                             DAG.getBasicBlock(NextMBB)));
1428
1429   return;
1430 }
1431
1432 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1433   // Retrieve successors.
1434   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1435   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1436
1437   if (isa<InlineAsm>(I.getCalledValue()))
1438     visitInlineAsm(&I);
1439   else
1440     LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1441
1442   // If the value of the invoke is used outside of its defining block, make it
1443   // available as a virtual register.
1444   if (!I.use_empty()) {
1445     DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1446     if (VMI != FuncInfo.ValueMap.end())
1447       CopyValueToVirtualRegister(&I, VMI->second);
1448   }
1449
1450   // Update successor info
1451   CurMBB->addSuccessor(Return);
1452   CurMBB->addSuccessor(LandingPad);
1453
1454   // Drop into normal successor.
1455   DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1456                           DAG.getBasicBlock(Return)));
1457 }
1458
1459 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1460 }
1461
1462 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1463 /// small case ranges).
1464 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1465                                                   CaseRecVector& WorkList,
1466                                                   Value* SV,
1467                                                   MachineBasicBlock* Default) {
1468   Case& BackCase  = *(CR.Range.second-1);
1469   
1470   // Size is the number of Cases represented by this range.
1471   unsigned Size = CR.Range.second - CR.Range.first;
1472   if (Size > 3)
1473     return false;  
1474   
1475   // Get the MachineFunction which holds the current MBB.  This is used when
1476   // inserting any additional MBBs necessary to represent the switch.
1477   MachineFunction *CurMF = CurMBB->getParent();  
1478
1479   // Figure out which block is immediately after the current one.
1480   MachineBasicBlock *NextBlock = 0;
1481   MachineFunction::iterator BBI = CR.CaseBB;
1482
1483   if (++BBI != CurMBB->getParent()->end())
1484     NextBlock = BBI;
1485
1486   // TODO: If any two of the cases has the same destination, and if one value
1487   // is the same as the other, but has one bit unset that the other has set,
1488   // use bit manipulation to do two compares at once.  For example:
1489   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1490     
1491   // Rearrange the case blocks so that the last one falls through if possible.
1492   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1493     // The last case block won't fall through into 'NextBlock' if we emit the
1494     // branches in this order.  See if rearranging a case value would help.
1495     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1496       if (I->BB == NextBlock) {
1497         std::swap(*I, BackCase);
1498         break;
1499       }
1500     }
1501   }
1502   
1503   // Create a CaseBlock record representing a conditional branch to
1504   // the Case's target mbb if the value being switched on SV is equal
1505   // to C.
1506   MachineBasicBlock *CurBlock = CR.CaseBB;
1507   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1508     MachineBasicBlock *FallThrough;
1509     if (I != E-1) {
1510       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1511       CurMF->insert(BBI, FallThrough);
1512     } else {
1513       // If the last case doesn't match, go to the default block.
1514       FallThrough = Default;
1515     }
1516
1517     Value *RHS, *LHS, *MHS;
1518     ISD::CondCode CC;
1519     if (I->High == I->Low) {
1520       // This is just small small case range :) containing exactly 1 case
1521       CC = ISD::SETEQ;
1522       LHS = SV; RHS = I->High; MHS = NULL;
1523     } else {
1524       CC = ISD::SETLE;
1525       LHS = I->Low; MHS = SV; RHS = I->High;
1526     }
1527     CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1528     
1529     // If emitting the first comparison, just call visitSwitchCase to emit the
1530     // code into the current block.  Otherwise, push the CaseBlock onto the
1531     // vector to be later processed by SDISel, and insert the node's MBB
1532     // before the next MBB.
1533     if (CurBlock == CurMBB)
1534       visitSwitchCase(CB);
1535     else
1536       SwitchCases.push_back(CB);
1537     
1538     CurBlock = FallThrough;
1539   }
1540
1541   return true;
1542 }
1543
1544 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1545   return !DisableJumpTables &&
1546           (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1547            TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1548 }
1549   
1550 /// handleJTSwitchCase - Emit jumptable for current switch case range
1551 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1552                                               CaseRecVector& WorkList,
1553                                               Value* SV,
1554                                               MachineBasicBlock* Default) {
1555   Case& FrontCase = *CR.Range.first;
1556   Case& BackCase  = *(CR.Range.second-1);
1557
1558   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1559   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
1560
1561   uint64_t TSize = 0;
1562   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1563        I!=E; ++I)
1564     TSize += I->size();
1565
1566   if (!areJTsAllowed(TLI) || TSize <= 3)
1567     return false;
1568   
1569   double Density = (double)TSize / (double)((Last - First) + 1ULL);  
1570   if (Density < 0.4)
1571     return false;
1572
1573   DOUT << "Lowering jump table\n"
1574        << "First entry: " << First << ". Last entry: " << Last << "\n"
1575        << "Size: " << TSize << ". Density: " << Density << "\n\n";
1576
1577   // Get the MachineFunction which holds the current MBB.  This is used when
1578   // inserting any additional MBBs necessary to represent the switch.
1579   MachineFunction *CurMF = CurMBB->getParent();
1580
1581   // Figure out which block is immediately after the current one.
1582   MachineBasicBlock *NextBlock = 0;
1583   MachineFunction::iterator BBI = CR.CaseBB;
1584
1585   if (++BBI != CurMBB->getParent()->end())
1586     NextBlock = BBI;
1587
1588   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1589
1590   // Create a new basic block to hold the code for loading the address
1591   // of the jump table, and jumping to it.  Update successor information;
1592   // we will either branch to the default case for the switch, or the jump
1593   // table.
1594   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1595   CurMF->insert(BBI, JumpTableBB);
1596   CR.CaseBB->addSuccessor(Default);
1597   CR.CaseBB->addSuccessor(JumpTableBB);
1598                 
1599   // Build a vector of destination BBs, corresponding to each target
1600   // of the jump table. If the value of the jump table slot corresponds to
1601   // a case statement, push the case's BB onto the vector, otherwise, push
1602   // the default BB.
1603   std::vector<MachineBasicBlock*> DestBBs;
1604   int64_t TEI = First;
1605   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1606     int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1607     int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1608     
1609     if ((Low <= TEI) && (TEI <= High)) {
1610       DestBBs.push_back(I->BB);
1611       if (TEI==High)
1612         ++I;
1613     } else {
1614       DestBBs.push_back(Default);
1615     }
1616   }
1617   
1618   // Update successor info. Add one edge to each unique successor.
1619   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());  
1620   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 
1621          E = DestBBs.end(); I != E; ++I) {
1622     if (!SuccsHandled[(*I)->getNumber()]) {
1623       SuccsHandled[(*I)->getNumber()] = true;
1624       JumpTableBB->addSuccessor(*I);
1625     }
1626   }
1627       
1628   // Create a jump table index for this jump table, or return an existing
1629   // one.
1630   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1631   
1632   // Set the jump table information so that we can codegen it as a second
1633   // MachineBasicBlock
1634   JumpTable JT(-1U, JTI, JumpTableBB, Default);
1635   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1636   if (CR.CaseBB == CurMBB)
1637     visitJumpTableHeader(JT, JTH);
1638         
1639   JTCases.push_back(JumpTableBlock(JTH, JT));
1640
1641   return true;
1642 }
1643
1644 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1645 /// 2 subtrees.
1646 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1647                                                    CaseRecVector& WorkList,
1648                                                    Value* SV,
1649                                                    MachineBasicBlock* Default) {
1650   // Get the MachineFunction which holds the current MBB.  This is used when
1651   // inserting any additional MBBs necessary to represent the switch.
1652   MachineFunction *CurMF = CurMBB->getParent();  
1653
1654   // Figure out which block is immediately after the current one.
1655   MachineBasicBlock *NextBlock = 0;
1656   MachineFunction::iterator BBI = CR.CaseBB;
1657
1658   if (++BBI != CurMBB->getParent()->end())
1659     NextBlock = BBI;
1660
1661   Case& FrontCase = *CR.Range.first;
1662   Case& BackCase  = *(CR.Range.second-1);
1663   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1664
1665   // Size is the number of Cases represented by this range.
1666   unsigned Size = CR.Range.second - CR.Range.first;
1667
1668   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1669   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
1670   double FMetric = 0;
1671   CaseItr Pivot = CR.Range.first + Size/2;
1672
1673   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1674   // (heuristically) allow us to emit JumpTable's later.
1675   uint64_t TSize = 0;
1676   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1677        I!=E; ++I)
1678     TSize += I->size();
1679
1680   uint64_t LSize = FrontCase.size();
1681   uint64_t RSize = TSize-LSize;
1682   DOUT << "Selecting best pivot: \n"
1683        << "First: " << First << ", Last: " << Last <<"\n"
1684        << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1685   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1686        J!=E; ++I, ++J) {
1687     int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1688     int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1689     assert((RBegin-LEnd>=1) && "Invalid case distance");
1690     double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1691     double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1692     double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1693     // Should always split in some non-trivial place
1694     DOUT <<"=>Step\n"
1695          << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1696          << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1697          << "Metric: " << Metric << "\n"; 
1698     if (FMetric < Metric) {
1699       Pivot = J;
1700       FMetric = Metric;
1701       DOUT << "Current metric set to: " << FMetric << "\n";
1702     }
1703
1704     LSize += J->size();
1705     RSize -= J->size();
1706   }
1707   if (areJTsAllowed(TLI)) {
1708     // If our case is dense we *really* should handle it earlier!
1709     assert((FMetric > 0) && "Should handle dense range earlier!");
1710   } else {
1711     Pivot = CR.Range.first + Size/2;
1712   }
1713   
1714   CaseRange LHSR(CR.Range.first, Pivot);
1715   CaseRange RHSR(Pivot, CR.Range.second);
1716   Constant *C = Pivot->Low;
1717   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1718       
1719   // We know that we branch to the LHS if the Value being switched on is
1720   // less than the Pivot value, C.  We use this to optimize our binary 
1721   // tree a bit, by recognizing that if SV is greater than or equal to the
1722   // LHS's Case Value, and that Case Value is exactly one less than the 
1723   // Pivot's Value, then we can branch directly to the LHS's Target,
1724   // rather than creating a leaf node for it.
1725   if ((LHSR.second - LHSR.first) == 1 &&
1726       LHSR.first->High == CR.GE &&
1727       cast<ConstantInt>(C)->getSExtValue() ==
1728       (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1729     TrueBB = LHSR.first->BB;
1730   } else {
1731     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1732     CurMF->insert(BBI, TrueBB);
1733     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1734   }
1735   
1736   // Similar to the optimization above, if the Value being switched on is
1737   // known to be less than the Constant CR.LT, and the current Case Value
1738   // is CR.LT - 1, then we can branch directly to the target block for
1739   // the current Case Value, rather than emitting a RHS leaf node for it.
1740   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1741       cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1742       (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1743     FalseBB = RHSR.first->BB;
1744   } else {
1745     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1746     CurMF->insert(BBI, FalseBB);
1747     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1748   }
1749
1750   // Create a CaseBlock record representing a conditional branch to
1751   // the LHS node if the value being switched on SV is less than C. 
1752   // Otherwise, branch to LHS.
1753   CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1754
1755   if (CR.CaseBB == CurMBB)
1756     visitSwitchCase(CB);
1757   else
1758     SwitchCases.push_back(CB);
1759
1760   return true;
1761 }
1762
1763 /// handleBitTestsSwitchCase - if current case range has few destination and
1764 /// range span less, than machine word bitwidth, encode case range into series
1765 /// of masks and emit bit tests with these masks.
1766 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1767                                                     CaseRecVector& WorkList,
1768                                                     Value* SV,
1769                                                     MachineBasicBlock* Default){
1770   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1771
1772   Case& FrontCase = *CR.Range.first;
1773   Case& BackCase  = *(CR.Range.second-1);
1774
1775   // Get the MachineFunction which holds the current MBB.  This is used when
1776   // inserting any additional MBBs necessary to represent the switch.
1777   MachineFunction *CurMF = CurMBB->getParent();  
1778
1779   unsigned numCmps = 0;
1780   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1781        I!=E; ++I) {
1782     // Single case counts one, case range - two.
1783     if (I->Low == I->High)
1784       numCmps +=1;
1785     else
1786       numCmps +=2;
1787   }
1788     
1789   // Count unique destinations
1790   SmallSet<MachineBasicBlock*, 4> Dests;
1791   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1792     Dests.insert(I->BB);
1793     if (Dests.size() > 3)
1794       // Don't bother the code below, if there are too much unique destinations
1795       return false;
1796   }
1797   DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1798        << "Total number of comparisons: " << numCmps << "\n";
1799   
1800   // Compute span of values.
1801   Constant* minValue = FrontCase.Low;
1802   Constant* maxValue = BackCase.High;
1803   uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1804                    cast<ConstantInt>(minValue)->getSExtValue();
1805   DOUT << "Compare range: " << range << "\n"
1806        << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1807        << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1808   
1809   if (range>=IntPtrBits ||
1810       (!(Dests.size() == 1 && numCmps >= 3) &&
1811        !(Dests.size() == 2 && numCmps >= 5) &&
1812        !(Dests.size() >= 3 && numCmps >= 6)))
1813     return false;
1814   
1815   DOUT << "Emitting bit tests\n";
1816   int64_t lowBound = 0;
1817     
1818   // Optimize the case where all the case values fit in a
1819   // word without having to subtract minValue. In this case,
1820   // we can optimize away the subtraction.
1821   if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1822       cast<ConstantInt>(maxValue)->getSExtValue() <  IntPtrBits) {
1823     range = cast<ConstantInt>(maxValue)->getSExtValue();
1824   } else {
1825     lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1826   }
1827     
1828   CaseBitsVector CasesBits;
1829   unsigned i, count = 0;
1830
1831   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1832     MachineBasicBlock* Dest = I->BB;
1833     for (i = 0; i < count; ++i)
1834       if (Dest == CasesBits[i].BB)
1835         break;
1836     
1837     if (i == count) {
1838       assert((count < 3) && "Too much destinations to test!");
1839       CasesBits.push_back(CaseBits(0, Dest, 0));
1840       count++;
1841     }
1842     
1843     uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1844     uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1845     
1846     for (uint64_t j = lo; j <= hi; j++) {
1847       CasesBits[i].Mask |=  1ULL << j;
1848       CasesBits[i].Bits++;
1849     }
1850       
1851   }
1852   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1853   
1854   BitTestInfo BTC;
1855
1856   // Figure out which block is immediately after the current one.
1857   MachineFunction::iterator BBI = CR.CaseBB;
1858   ++BBI;
1859
1860   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1861
1862   DOUT << "Cases:\n";
1863   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1864     DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1865          << ", BB: " << CasesBits[i].BB << "\n";
1866
1867     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1868     CurMF->insert(BBI, CaseBB);
1869     BTC.push_back(BitTestCase(CasesBits[i].Mask,
1870                               CaseBB,
1871                               CasesBits[i].BB));
1872   }
1873   
1874   BitTestBlock BTB(lowBound, range, SV,
1875                    -1U, (CR.CaseBB == CurMBB),
1876                    CR.CaseBB, Default, BTC);
1877
1878   if (CR.CaseBB == CurMBB)
1879     visitBitTestHeader(BTB);
1880   
1881   BitTestCases.push_back(BTB);
1882
1883   return true;
1884 }
1885
1886
1887 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1888 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1889                                           const SwitchInst& SI) {
1890   unsigned numCmps = 0;
1891
1892   // Start with "simple" cases
1893   for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1894     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1895     Cases.push_back(Case(SI.getSuccessorValue(i),
1896                          SI.getSuccessorValue(i),
1897                          SMBB));
1898   }
1899   std::sort(Cases.begin(), Cases.end(), CaseCmp());
1900
1901   // Merge case into clusters
1902   if (Cases.size()>=2)
1903     // Must recompute end() each iteration because it may be
1904     // invalidated by erase if we hold on to it
1905     for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1906       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1907       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1908       MachineBasicBlock* nextBB = J->BB;
1909       MachineBasicBlock* currentBB = I->BB;
1910
1911       // If the two neighboring cases go to the same destination, merge them
1912       // into a single case.
1913       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1914         I->High = J->High;
1915         J = Cases.erase(J);
1916       } else {
1917         I = J++;
1918       }
1919     }
1920
1921   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1922     if (I->Low != I->High)
1923       // A range counts double, since it requires two compares.
1924       ++numCmps;
1925   }
1926
1927   return numCmps;
1928 }
1929
1930 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {  
1931   // Figure out which block is immediately after the current one.
1932   MachineBasicBlock *NextBlock = 0;
1933   MachineFunction::iterator BBI = CurMBB;
1934
1935   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1936
1937   // If there is only the default destination, branch to it if it is not the
1938   // next basic block.  Otherwise, just fall through.
1939   if (SI.getNumOperands() == 2) {
1940     // Update machine-CFG edges.
1941
1942     // If this is not a fall-through branch, emit the branch.
1943     CurMBB->addSuccessor(Default);
1944     if (Default != NextBlock)
1945       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1946                               DAG.getBasicBlock(Default)));
1947     
1948     return;
1949   }
1950   
1951   // If there are any non-default case statements, create a vector of Cases
1952   // representing each one, and sort the vector so that we can efficiently
1953   // create a binary search tree from them.
1954   CaseVector Cases;
1955   unsigned numCmps = Clusterify(Cases, SI);
1956   DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1957        << ". Total compares: " << numCmps << "\n";
1958
1959   // Get the Value to be switched on and default basic blocks, which will be
1960   // inserted into CaseBlock records, representing basic blocks in the binary
1961   // search tree.
1962   Value *SV = SI.getOperand(0);
1963
1964   // Push the initial CaseRec onto the worklist
1965   CaseRecVector WorkList;
1966   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1967
1968   while (!WorkList.empty()) {
1969     // Grab a record representing a case range to process off the worklist
1970     CaseRec CR = WorkList.back();
1971     WorkList.pop_back();
1972
1973     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1974       continue;
1975     
1976     // If the range has few cases (two or less) emit a series of specific
1977     // tests.
1978     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1979       continue;
1980     
1981     // If the switch has more than 5 blocks, and at least 40% dense, and the 
1982     // target supports indirect branches, then emit a jump table rather than 
1983     // lowering the switch to a binary tree of conditional branches.
1984     if (handleJTSwitchCase(CR, WorkList, SV, Default))
1985       continue;
1986           
1987     // Emit binary tree. We need to pick a pivot, and push left and right ranges
1988     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1989     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1990   }
1991 }
1992
1993
1994 void SelectionDAGLowering::visitSub(User &I) {
1995   // -0.0 - X --> fneg
1996   const Type *Ty = I.getType();
1997   if (isa<VectorType>(Ty)) {
1998     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1999       const VectorType *DestTy = cast<VectorType>(I.getType());
2000       const Type *ElTy = DestTy->getElementType();
2001       if (ElTy->isFloatingPoint()) {
2002         unsigned VL = DestTy->getNumElements();
2003         std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2004         Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2005         if (CV == CNZ) {
2006           SDValue Op2 = getValue(I.getOperand(1));
2007           setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2008           return;
2009         }
2010       }
2011     }
2012   }
2013   if (Ty->isFloatingPoint()) {
2014     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2015       if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2016         SDValue Op2 = getValue(I.getOperand(1));
2017         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2018         return;
2019       }
2020   }
2021
2022   visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2023 }
2024
2025 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2026   SDValue Op1 = getValue(I.getOperand(0));
2027   SDValue Op2 = getValue(I.getOperand(1));
2028   
2029   setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2030 }
2031
2032 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2033   SDValue Op1 = getValue(I.getOperand(0));
2034   SDValue Op2 = getValue(I.getOperand(1));
2035   if (!isa<VectorType>(I.getType())) {
2036     if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2037       Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2038     else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2039       Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2040   }
2041   
2042   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2043 }
2044
2045 void SelectionDAGLowering::visitICmp(User &I) {
2046   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2047   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2048     predicate = IC->getPredicate();
2049   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2050     predicate = ICmpInst::Predicate(IC->getPredicate());
2051   SDValue Op1 = getValue(I.getOperand(0));
2052   SDValue Op2 = getValue(I.getOperand(1));
2053   ISD::CondCode Opcode;
2054   switch (predicate) {
2055     case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2056     case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2057     case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2058     case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2059     case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2060     case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2061     case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2062     case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2063     case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2064     case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2065     default:
2066       assert(!"Invalid ICmp predicate value");
2067       Opcode = ISD::SETEQ;
2068       break;
2069   }
2070   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2071 }
2072
2073 void SelectionDAGLowering::visitFCmp(User &I) {
2074   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2075   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2076     predicate = FC->getPredicate();
2077   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2078     predicate = FCmpInst::Predicate(FC->getPredicate());
2079   SDValue Op1 = getValue(I.getOperand(0));
2080   SDValue Op2 = getValue(I.getOperand(1));
2081   ISD::CondCode Condition, FOC, FPC;
2082   switch (predicate) {
2083     case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2084     case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2085     case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2086     case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2087     case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2088     case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2089     case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2090     case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2091     case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2092     case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2093     case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2094     case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2095     case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2096     case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2097     case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2098     case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2099     default:
2100       assert(!"Invalid FCmp predicate value");
2101       FOC = FPC = ISD::SETFALSE;
2102       break;
2103   }
2104   if (FiniteOnlyFPMath())
2105     Condition = FOC;
2106   else 
2107     Condition = FPC;
2108   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2109 }
2110
2111 void SelectionDAGLowering::visitVICmp(User &I) {
2112   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2113   if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2114     predicate = IC->getPredicate();
2115   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2116     predicate = ICmpInst::Predicate(IC->getPredicate());
2117   SDValue Op1 = getValue(I.getOperand(0));
2118   SDValue Op2 = getValue(I.getOperand(1));
2119   ISD::CondCode Opcode;
2120   switch (predicate) {
2121     case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2122     case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2123     case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2124     case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2125     case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2126     case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2127     case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2128     case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2129     case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2130     case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2131     default:
2132       assert(!"Invalid ICmp predicate value");
2133       Opcode = ISD::SETEQ;
2134       break;
2135   }
2136   setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2137 }
2138
2139 void SelectionDAGLowering::visitVFCmp(User &I) {
2140   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2141   if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2142     predicate = FC->getPredicate();
2143   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2144     predicate = FCmpInst::Predicate(FC->getPredicate());
2145   SDValue Op1 = getValue(I.getOperand(0));
2146   SDValue Op2 = getValue(I.getOperand(1));
2147   ISD::CondCode Condition, FOC, FPC;
2148   switch (predicate) {
2149     case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2150     case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2151     case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2152     case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2153     case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2154     case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2155     case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2156     case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2157     case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2158     case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2159     case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2160     case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2161     case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2162     case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2163     case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2164     case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2165     default:
2166       assert(!"Invalid VFCmp predicate value");
2167       FOC = FPC = ISD::SETFALSE;
2168       break;
2169   }
2170   if (FiniteOnlyFPMath())
2171     Condition = FOC;
2172   else 
2173     Condition = FPC;
2174     
2175   MVT DestVT = TLI.getValueType(I.getType());
2176     
2177   setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2178 }
2179
2180 void SelectionDAGLowering::visitSelect(User &I) {
2181   SDValue Cond     = getValue(I.getOperand(0));
2182   SDValue TrueVal  = getValue(I.getOperand(1));
2183   SDValue FalseVal = getValue(I.getOperand(2));
2184   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2185                            TrueVal, FalseVal));
2186 }
2187
2188
2189 void SelectionDAGLowering::visitTrunc(User &I) {
2190   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2191   SDValue N = getValue(I.getOperand(0));
2192   MVT DestVT = TLI.getValueType(I.getType());
2193   setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2194 }
2195
2196 void SelectionDAGLowering::visitZExt(User &I) {
2197   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2198   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2199   SDValue N = getValue(I.getOperand(0));
2200   MVT DestVT = TLI.getValueType(I.getType());
2201   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2202 }
2203
2204 void SelectionDAGLowering::visitSExt(User &I) {
2205   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2206   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2207   SDValue N = getValue(I.getOperand(0));
2208   MVT DestVT = TLI.getValueType(I.getType());
2209   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2210 }
2211
2212 void SelectionDAGLowering::visitFPTrunc(User &I) {
2213   // FPTrunc is never a no-op cast, no need to check
2214   SDValue N = getValue(I.getOperand(0));
2215   MVT DestVT = TLI.getValueType(I.getType());
2216   setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2217 }
2218
2219 void SelectionDAGLowering::visitFPExt(User &I){ 
2220   // FPTrunc is never a no-op cast, no need to check
2221   SDValue N = getValue(I.getOperand(0));
2222   MVT DestVT = TLI.getValueType(I.getType());
2223   setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2224 }
2225
2226 void SelectionDAGLowering::visitFPToUI(User &I) { 
2227   // FPToUI is never a no-op cast, no need to check
2228   SDValue N = getValue(I.getOperand(0));
2229   MVT DestVT = TLI.getValueType(I.getType());
2230   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2231 }
2232
2233 void SelectionDAGLowering::visitFPToSI(User &I) {
2234   // FPToSI is never a no-op cast, no need to check
2235   SDValue N = getValue(I.getOperand(0));
2236   MVT DestVT = TLI.getValueType(I.getType());
2237   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2238 }
2239
2240 void SelectionDAGLowering::visitUIToFP(User &I) { 
2241   // UIToFP is never a no-op cast, no need to check
2242   SDValue N = getValue(I.getOperand(0));
2243   MVT DestVT = TLI.getValueType(I.getType());
2244   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2245 }
2246
2247 void SelectionDAGLowering::visitSIToFP(User &I){ 
2248   // UIToFP is never a no-op cast, no need to check
2249   SDValue N = getValue(I.getOperand(0));
2250   MVT DestVT = TLI.getValueType(I.getType());
2251   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2252 }
2253
2254 void SelectionDAGLowering::visitPtrToInt(User &I) {
2255   // What to do depends on the size of the integer and the size of the pointer.
2256   // We can either truncate, zero extend, or no-op, accordingly.
2257   SDValue N = getValue(I.getOperand(0));
2258   MVT SrcVT = N.getValueType();
2259   MVT DestVT = TLI.getValueType(I.getType());
2260   SDValue Result;
2261   if (DestVT.bitsLT(SrcVT))
2262     Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2263   else 
2264     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2265     Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2266   setValue(&I, Result);
2267 }
2268
2269 void SelectionDAGLowering::visitIntToPtr(User &I) {
2270   // What to do depends on the size of the integer and the size of the pointer.
2271   // We can either truncate, zero extend, or no-op, accordingly.
2272   SDValue N = getValue(I.getOperand(0));
2273   MVT SrcVT = N.getValueType();
2274   MVT DestVT = TLI.getValueType(I.getType());
2275   if (DestVT.bitsLT(SrcVT))
2276     setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2277   else 
2278     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2279     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2280 }
2281
2282 void SelectionDAGLowering::visitBitCast(User &I) { 
2283   SDValue N = getValue(I.getOperand(0));
2284   MVT DestVT = TLI.getValueType(I.getType());
2285
2286   // BitCast assures us that source and destination are the same size so this 
2287   // is either a BIT_CONVERT or a no-op.
2288   if (DestVT != N.getValueType())
2289     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2290   else
2291     setValue(&I, N); // noop cast.
2292 }
2293
2294 void SelectionDAGLowering::visitInsertElement(User &I) {
2295   SDValue InVec = getValue(I.getOperand(0));
2296   SDValue InVal = getValue(I.getOperand(1));
2297   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2298                                 getValue(I.getOperand(2)));
2299
2300   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2301                            TLI.getValueType(I.getType()),
2302                            InVec, InVal, InIdx));
2303 }
2304
2305 void SelectionDAGLowering::visitExtractElement(User &I) {
2306   SDValue InVec = getValue(I.getOperand(0));
2307   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2308                                 getValue(I.getOperand(1)));
2309   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2310                            TLI.getValueType(I.getType()), InVec, InIdx));
2311 }
2312
2313 void SelectionDAGLowering::visitShuffleVector(User &I) {
2314   SDValue V1   = getValue(I.getOperand(0));
2315   SDValue V2   = getValue(I.getOperand(1));
2316   SDValue Mask = getValue(I.getOperand(2));
2317
2318   setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2319                            TLI.getValueType(I.getType()),
2320                            V1, V2, Mask));
2321 }
2322
2323 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2324   const Value *Op0 = I.getOperand(0);
2325   const Value *Op1 = I.getOperand(1);
2326   const Type *AggTy = I.getType();
2327   const Type *ValTy = Op1->getType();
2328   bool IntoUndef = isa<UndefValue>(Op0);
2329   bool FromUndef = isa<UndefValue>(Op1);
2330
2331   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2332                                             I.idx_begin(), I.idx_end());
2333
2334   SmallVector<MVT, 4> AggValueVTs;
2335   ComputeValueVTs(TLI, AggTy, AggValueVTs);
2336   SmallVector<MVT, 4> ValValueVTs;
2337   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2338
2339   unsigned NumAggValues = AggValueVTs.size();
2340   unsigned NumValValues = ValValueVTs.size();
2341   SmallVector<SDValue, 4> Values(NumAggValues);
2342
2343   SDValue Agg = getValue(Op0);
2344   SDValue Val = getValue(Op1);
2345   unsigned i = 0;
2346   // Copy the beginning value(s) from the original aggregate.
2347   for (; i != LinearIndex; ++i)
2348     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2349                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2350   // Copy values from the inserted value(s).
2351   for (; i != LinearIndex + NumValValues; ++i)
2352     Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2353                 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2354   // Copy remaining value(s) from the original aggregate.
2355   for (; i != NumAggValues; ++i)
2356     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2357                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2358
2359   setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2360                                   &Values[0], NumAggValues));
2361 }
2362
2363 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2364   const Value *Op0 = I.getOperand(0);
2365   const Type *AggTy = Op0->getType();
2366   const Type *ValTy = I.getType();
2367   bool OutOfUndef = isa<UndefValue>(Op0);
2368
2369   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2370                                             I.idx_begin(), I.idx_end());
2371
2372   SmallVector<MVT, 4> ValValueVTs;
2373   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2374
2375   unsigned NumValValues = ValValueVTs.size();
2376   SmallVector<SDValue, 4> Values(NumValValues);
2377
2378   SDValue Agg = getValue(Op0);
2379   // Copy out the selected value(s).
2380   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2381     Values[i - LinearIndex] =
2382       OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2383                    SDValue(Agg.getNode(), Agg.getResNo() + i);
2384
2385   setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2386                                   &Values[0], NumValValues));
2387 }
2388
2389
2390 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2391   SDValue N = getValue(I.getOperand(0));
2392   const Type *Ty = I.getOperand(0)->getType();
2393
2394   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2395        OI != E; ++OI) {
2396     Value *Idx = *OI;
2397     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2398       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2399       if (Field) {
2400         // N = N + Offset
2401         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2402         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2403                         DAG.getIntPtrConstant(Offset));
2404       }
2405       Ty = StTy->getElementType(Field);
2406     } else {
2407       Ty = cast<SequentialType>(Ty)->getElementType();
2408
2409       // If this is a constant subscript, handle it quickly.
2410       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2411         if (CI->getZExtValue() == 0) continue;
2412         uint64_t Offs = 
2413             TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2414         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2415                         DAG.getIntPtrConstant(Offs));
2416         continue;
2417       }
2418       
2419       // N = N + Idx * ElementSize;
2420       uint64_t ElementSize = TD->getABITypeSize(Ty);
2421       SDValue IdxN = getValue(Idx);
2422
2423       // If the index is smaller or larger than intptr_t, truncate or extend
2424       // it.
2425       if (IdxN.getValueType().bitsLT(N.getValueType()))
2426         IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2427       else if (IdxN.getValueType().bitsGT(N.getValueType()))
2428         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2429
2430       // If this is a multiply by a power of two, turn it into a shl
2431       // immediately.  This is a very common case.
2432       if (ElementSize != 1) {
2433         if (isPowerOf2_64(ElementSize)) {
2434           unsigned Amt = Log2_64(ElementSize);
2435           IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2436                              DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2437         } else {
2438           SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2439           IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2440         }
2441       }
2442
2443       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2444     }
2445   }
2446   setValue(&I, N);
2447 }
2448
2449 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2450   // If this is a fixed sized alloca in the entry block of the function,
2451   // allocate it statically on the stack.
2452   if (FuncInfo.StaticAllocaMap.count(&I))
2453     return;   // getValue will auto-populate this.
2454
2455   const Type *Ty = I.getAllocatedType();
2456   uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2457   unsigned Align =
2458     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2459              I.getAlignment());
2460
2461   SDValue AllocSize = getValue(I.getArraySize());
2462   MVT IntPtr = TLI.getPointerTy();
2463   if (IntPtr.bitsLT(AllocSize.getValueType()))
2464     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2465   else if (IntPtr.bitsGT(AllocSize.getValueType()))
2466     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2467
2468   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2469                           DAG.getIntPtrConstant(TySize));
2470
2471   // Handle alignment.  If the requested alignment is less than or equal to
2472   // the stack alignment, ignore it.  If the size is greater than or equal to
2473   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2474   unsigned StackAlign =
2475     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2476   if (Align <= StackAlign)
2477     Align = 0;
2478
2479   // Round the size of the allocation up to the stack alignment size
2480   // by add SA-1 to the size.
2481   AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2482                           DAG.getIntPtrConstant(StackAlign-1));
2483   // Mask out the low bits for alignment purposes.
2484   AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2485                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2486
2487   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2488   const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2489                                                     MVT::Other);
2490   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2491   setValue(&I, DSA);
2492   DAG.setRoot(DSA.getValue(1));
2493
2494   // Inform the Frame Information that we have just allocated a variable-sized
2495   // object.
2496   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2497 }
2498
2499 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2500   const Value *SV = I.getOperand(0);
2501   SDValue Ptr = getValue(SV);
2502
2503   const Type *Ty = I.getType();
2504   bool isVolatile = I.isVolatile();
2505   unsigned Alignment = I.getAlignment();
2506
2507   SmallVector<MVT, 4> ValueVTs;
2508   SmallVector<uint64_t, 4> Offsets;
2509   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2510   unsigned NumValues = ValueVTs.size();
2511   if (NumValues == 0)
2512     return;
2513
2514   SDValue Root;
2515   bool ConstantMemory = false;
2516   if (I.isVolatile())
2517     // Serialize volatile loads with other side effects.
2518     Root = getRoot();
2519   else if (AA->pointsToConstantMemory(SV)) {
2520     // Do not serialize (non-volatile) loads of constant memory with anything.
2521     Root = DAG.getEntryNode();
2522     ConstantMemory = true;
2523   } else {
2524     // Do not serialize non-volatile loads against each other.
2525     Root = DAG.getRoot();
2526   }
2527
2528   SmallVector<SDValue, 4> Values(NumValues);
2529   SmallVector<SDValue, 4> Chains(NumValues);
2530   MVT PtrVT = Ptr.getValueType();
2531   for (unsigned i = 0; i != NumValues; ++i) {
2532     SDValue L = DAG.getLoad(ValueVTs[i], Root,
2533                               DAG.getNode(ISD::ADD, PtrVT, Ptr,
2534                                           DAG.getConstant(Offsets[i], PtrVT)),
2535                               SV, Offsets[i],
2536                               isVolatile, Alignment);
2537     Values[i] = L;
2538     Chains[i] = L.getValue(1);
2539   }
2540   
2541   if (!ConstantMemory) {
2542     SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2543                                   &Chains[0], NumValues);
2544     if (isVolatile)
2545       DAG.setRoot(Chain);
2546     else
2547       PendingLoads.push_back(Chain);
2548   }
2549
2550   setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2551                                   &Values[0], NumValues));
2552 }
2553
2554
2555 void SelectionDAGLowering::visitStore(StoreInst &I) {
2556   Value *SrcV = I.getOperand(0);
2557   Value *PtrV = I.getOperand(1);
2558
2559   SmallVector<MVT, 4> ValueVTs;
2560   SmallVector<uint64_t, 4> Offsets;
2561   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2562   unsigned NumValues = ValueVTs.size();
2563   if (NumValues == 0)
2564     return;
2565
2566   // Get the lowered operands. Note that we do this after
2567   // checking if NumResults is zero, because with zero results
2568   // the operands won't have values in the map.
2569   SDValue Src = getValue(SrcV);
2570   SDValue Ptr = getValue(PtrV);
2571
2572   SDValue Root = getRoot();
2573   SmallVector<SDValue, 4> Chains(NumValues);
2574   MVT PtrVT = Ptr.getValueType();
2575   bool isVolatile = I.isVolatile();
2576   unsigned Alignment = I.getAlignment();
2577   for (unsigned i = 0; i != NumValues; ++i)
2578     Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2579                              DAG.getNode(ISD::ADD, PtrVT, Ptr,
2580                                          DAG.getConstant(Offsets[i], PtrVT)),
2581                              PtrV, Offsets[i],
2582                              isVolatile, Alignment);
2583
2584   DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2585 }
2586
2587 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2588 /// node.
2589 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 
2590                                                 unsigned Intrinsic) {
2591   bool HasChain = !I.doesNotAccessMemory();
2592   bool OnlyLoad = HasChain && I.onlyReadsMemory();
2593
2594   // Build the operand list.
2595   SmallVector<SDValue, 8> Ops;
2596   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
2597     if (OnlyLoad) {
2598       // We don't need to serialize loads against other loads.
2599       Ops.push_back(DAG.getRoot());
2600     } else { 
2601       Ops.push_back(getRoot());
2602     }
2603   }
2604   
2605   // Add the intrinsic ID as an integer operand.
2606   Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2607
2608   // Add all operands of the call to the operand list.
2609   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2610     SDValue Op = getValue(I.getOperand(i));
2611     assert(TLI.isTypeLegal(Op.getValueType()) &&
2612            "Intrinsic uses a non-legal type?");
2613     Ops.push_back(Op);
2614   }
2615
2616   std::vector<MVT> VTs;
2617   if (I.getType() != Type::VoidTy) {
2618     MVT VT = TLI.getValueType(I.getType());
2619     if (VT.isVector()) {
2620       const VectorType *DestTy = cast<VectorType>(I.getType());
2621       MVT EltVT = TLI.getValueType(DestTy->getElementType());
2622       
2623       VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2624       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2625     }
2626     
2627     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2628     VTs.push_back(VT);
2629   }
2630   if (HasChain)
2631     VTs.push_back(MVT::Other);
2632
2633   const MVT *VTList = DAG.getNodeValueTypes(VTs);
2634
2635   // Create the node.
2636   SDValue Result;
2637   if (!HasChain)
2638     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2639                          &Ops[0], Ops.size());
2640   else if (I.getType() != Type::VoidTy)
2641     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2642                          &Ops[0], Ops.size());
2643   else
2644     Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2645                          &Ops[0], Ops.size());
2646
2647   if (HasChain) {
2648     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2649     if (OnlyLoad)
2650       PendingLoads.push_back(Chain);
2651     else
2652       DAG.setRoot(Chain);
2653   }
2654   if (I.getType() != Type::VoidTy) {
2655     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2656       MVT VT = TLI.getValueType(PTy);
2657       Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2658     } 
2659     setValue(&I, Result);
2660   }
2661 }
2662
2663 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2664 static GlobalVariable *ExtractTypeInfo(Value *V) {
2665   V = V->stripPointerCasts();
2666   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2667   assert ((GV || isa<ConstantPointerNull>(V)) &&
2668           "TypeInfo must be a global variable or NULL");
2669   return GV;
2670 }
2671
2672 namespace llvm {
2673
2674 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2675 /// call, and add them to the specified machine basic block.
2676 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2677                   MachineBasicBlock *MBB) {
2678   // Inform the MachineModuleInfo of the personality for this landing pad.
2679   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2680   assert(CE->getOpcode() == Instruction::BitCast &&
2681          isa<Function>(CE->getOperand(0)) &&
2682          "Personality should be a function");
2683   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2684
2685   // Gather all the type infos for this landing pad and pass them along to
2686   // MachineModuleInfo.
2687   std::vector<GlobalVariable *> TyInfo;
2688   unsigned N = I.getNumOperands();
2689
2690   for (unsigned i = N - 1; i > 2; --i) {
2691     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2692       unsigned FilterLength = CI->getZExtValue();
2693       unsigned FirstCatch = i + FilterLength + !FilterLength;
2694       assert (FirstCatch <= N && "Invalid filter length");
2695
2696       if (FirstCatch < N) {
2697         TyInfo.reserve(N - FirstCatch);
2698         for (unsigned j = FirstCatch; j < N; ++j)
2699           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2700         MMI->addCatchTypeInfo(MBB, TyInfo);
2701         TyInfo.clear();
2702       }
2703
2704       if (!FilterLength) {
2705         // Cleanup.
2706         MMI->addCleanup(MBB);
2707       } else {
2708         // Filter.
2709         TyInfo.reserve(FilterLength - 1);
2710         for (unsigned j = i + 1; j < FirstCatch; ++j)
2711           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2712         MMI->addFilterTypeInfo(MBB, TyInfo);
2713         TyInfo.clear();
2714       }
2715
2716       N = i;
2717     }
2718   }
2719
2720   if (N > 3) {
2721     TyInfo.reserve(N - 3);
2722     for (unsigned j = 3; j < N; ++j)
2723       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2724     MMI->addCatchTypeInfo(MBB, TyInfo);
2725   }
2726 }
2727
2728 }
2729
2730 /// Inlined utility function to implement binary input atomic intrinsics for 
2731 /// visitIntrinsicCall: I is a call instruction
2732 ///                     Op is the associated NodeType for I
2733 const char *
2734 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2735   SDValue Root = getRoot();   
2736   SDValue L = DAG.getAtomic(Op, Root, 
2737                               getValue(I.getOperand(1)), 
2738                               getValue(I.getOperand(2)),
2739                               I.getOperand(1));
2740   setValue(&I, L);
2741   DAG.setRoot(L.getValue(1));
2742   return 0;
2743 }
2744
2745 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
2746 /// we want to emit this as a call to a named external function, return the name
2747 /// otherwise lower it and return null.
2748 const char *
2749 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2750   switch (Intrinsic) {
2751   default:
2752     // By default, turn this into a target intrinsic node.
2753     visitTargetIntrinsic(I, Intrinsic);
2754     return 0;
2755   case Intrinsic::vastart:  visitVAStart(I); return 0;
2756   case Intrinsic::vaend:    visitVAEnd(I); return 0;
2757   case Intrinsic::vacopy:   visitVACopy(I); return 0;
2758   case Intrinsic::returnaddress:
2759     setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2760                              getValue(I.getOperand(1))));
2761     return 0;
2762   case Intrinsic::frameaddress:
2763     setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2764                              getValue(I.getOperand(1))));
2765     return 0;
2766   case Intrinsic::setjmp:
2767     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2768     break;
2769   case Intrinsic::longjmp:
2770     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2771     break;
2772   case Intrinsic::memcpy_i32:
2773   case Intrinsic::memcpy_i64: {
2774     SDValue Op1 = getValue(I.getOperand(1));
2775     SDValue Op2 = getValue(I.getOperand(2));
2776     SDValue Op3 = getValue(I.getOperand(3));
2777     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2778     DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2779                               I.getOperand(1), 0, I.getOperand(2), 0));
2780     return 0;
2781   }
2782   case Intrinsic::memset_i32:
2783   case Intrinsic::memset_i64: {
2784     SDValue Op1 = getValue(I.getOperand(1));
2785     SDValue Op2 = getValue(I.getOperand(2));
2786     SDValue Op3 = getValue(I.getOperand(3));
2787     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2788     DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2789                               I.getOperand(1), 0));
2790     return 0;
2791   }
2792   case Intrinsic::memmove_i32:
2793   case Intrinsic::memmove_i64: {
2794     SDValue Op1 = getValue(I.getOperand(1));
2795     SDValue Op2 = getValue(I.getOperand(2));
2796     SDValue Op3 = getValue(I.getOperand(3));
2797     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2798
2799     // If the source and destination are known to not be aliases, we can
2800     // lower memmove as memcpy.
2801     uint64_t Size = -1ULL;
2802     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2803       Size = C->getValue();
2804     if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2805         AliasAnalysis::NoAlias) {
2806       DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2807                                 I.getOperand(1), 0, I.getOperand(2), 0));
2808       return 0;
2809     }
2810
2811     DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2812                                I.getOperand(1), 0, I.getOperand(2), 0));
2813     return 0;
2814   }
2815   case Intrinsic::dbg_stoppoint: {
2816     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2817     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2818     if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2819       DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2820       assert(DD && "Not a debug information descriptor");
2821       DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
2822                                       SPI.getLine(),
2823                                       SPI.getColumn(),
2824                                       cast<CompileUnitDesc>(DD)));
2825     }
2826
2827     return 0;
2828   }
2829   case Intrinsic::dbg_region_start: {
2830     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2831     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2832     if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2833       unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2834       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
2835     }
2836
2837     return 0;
2838   }
2839   case Intrinsic::dbg_region_end: {
2840     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2841     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2842     if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2843       unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2844       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
2845     }
2846
2847     return 0;
2848   }
2849   case Intrinsic::dbg_func_start: {
2850     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2851     if (!MMI) return 0;
2852     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2853     Value *SP = FSI.getSubprogram();
2854     if (SP && MMI->Verify(SP)) {
2855       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2856       // what (most?) gdb expects.
2857       DebugInfoDesc *DD = MMI->getDescFor(SP);
2858       assert(DD && "Not a debug information descriptor");
2859       SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2860       const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2861       unsigned SrcFile = MMI->RecordSource(CompileUnit);
2862       // Record the source line but does create a label. It will be emitted
2863       // at asm emission time.
2864       MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2865     }
2866
2867     return 0;
2868   }
2869   case Intrinsic::dbg_declare: {
2870     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2871     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2872     Value *Variable = DI.getVariable();
2873     if (MMI && Variable && MMI->Verify(Variable))
2874       DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2875                               getValue(DI.getAddress()), getValue(Variable)));
2876     return 0;
2877   }
2878     
2879   case Intrinsic::eh_exception: {
2880     if (!CurMBB->isLandingPad()) {
2881       // FIXME: Mark exception register as live in.  Hack for PR1508.
2882       unsigned Reg = TLI.getExceptionAddressRegister();
2883       if (Reg) CurMBB->addLiveIn(Reg);
2884     }
2885     // Insert the EXCEPTIONADDR instruction.
2886     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2887     SDValue Ops[1];
2888     Ops[0] = DAG.getRoot();
2889     SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2890     setValue(&I, Op);
2891     DAG.setRoot(Op.getValue(1));
2892     return 0;
2893   }
2894
2895   case Intrinsic::eh_selector_i32:
2896   case Intrinsic::eh_selector_i64: {
2897     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2898     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2899                          MVT::i32 : MVT::i64);
2900     
2901     if (MMI) {
2902       if (CurMBB->isLandingPad())
2903         AddCatchInfo(I, MMI, CurMBB);
2904       else {
2905 #ifndef NDEBUG
2906         FuncInfo.CatchInfoLost.insert(&I);
2907 #endif
2908         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
2909         unsigned Reg = TLI.getExceptionSelectorRegister();
2910         if (Reg) CurMBB->addLiveIn(Reg);
2911       }
2912
2913       // Insert the EHSELECTION instruction.
2914       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2915       SDValue Ops[2];
2916       Ops[0] = getValue(I.getOperand(1));
2917       Ops[1] = getRoot();
2918       SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2919       setValue(&I, Op);
2920       DAG.setRoot(Op.getValue(1));
2921     } else {
2922       setValue(&I, DAG.getConstant(0, VT));
2923     }
2924     
2925     return 0;
2926   }
2927
2928   case Intrinsic::eh_typeid_for_i32:
2929   case Intrinsic::eh_typeid_for_i64: {
2930     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2931     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2932                          MVT::i32 : MVT::i64);
2933     
2934     if (MMI) {
2935       // Find the type id for the given typeinfo.
2936       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2937
2938       unsigned TypeID = MMI->getTypeIDFor(GV);
2939       setValue(&I, DAG.getConstant(TypeID, VT));
2940     } else {
2941       // Return something different to eh_selector.
2942       setValue(&I, DAG.getConstant(1, VT));
2943     }
2944
2945     return 0;
2946   }
2947
2948   case Intrinsic::eh_return: {
2949     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2950
2951     if (MMI) {
2952       MMI->setCallsEHReturn(true);
2953       DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2954                               MVT::Other,
2955                               getControlRoot(),
2956                               getValue(I.getOperand(1)),
2957                               getValue(I.getOperand(2))));
2958     } else {
2959       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2960     }
2961
2962     return 0;
2963   }
2964
2965    case Intrinsic::eh_unwind_init: {    
2966      if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2967        MMI->setCallsUnwindInit(true);
2968      }
2969
2970      return 0;
2971    }
2972
2973    case Intrinsic::eh_dwarf_cfa: {
2974      MVT VT = getValue(I.getOperand(1)).getValueType();
2975      SDValue CfaArg;
2976      if (VT.bitsGT(TLI.getPointerTy()))
2977        CfaArg = DAG.getNode(ISD::TRUNCATE,
2978                             TLI.getPointerTy(), getValue(I.getOperand(1)));
2979      else
2980        CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
2981                             TLI.getPointerTy(), getValue(I.getOperand(1)));
2982
2983      SDValue Offset = DAG.getNode(ISD::ADD,
2984                                     TLI.getPointerTy(),
2985                                     DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
2986                                                 TLI.getPointerTy()),
2987                                     CfaArg);
2988      setValue(&I, DAG.getNode(ISD::ADD,
2989                               TLI.getPointerTy(),
2990                               DAG.getNode(ISD::FRAMEADDR,
2991                                           TLI.getPointerTy(),
2992                                           DAG.getConstant(0,
2993                                                           TLI.getPointerTy())),
2994                               Offset));
2995      return 0;
2996   }
2997
2998   case Intrinsic::sqrt:
2999     setValue(&I, DAG.getNode(ISD::FSQRT,
3000                              getValue(I.getOperand(1)).getValueType(),
3001                              getValue(I.getOperand(1))));
3002     return 0;
3003   case Intrinsic::powi:
3004     setValue(&I, DAG.getNode(ISD::FPOWI,
3005                              getValue(I.getOperand(1)).getValueType(),
3006                              getValue(I.getOperand(1)),
3007                              getValue(I.getOperand(2))));
3008     return 0;
3009   case Intrinsic::sin:
3010     setValue(&I, DAG.getNode(ISD::FSIN,
3011                              getValue(I.getOperand(1)).getValueType(),
3012                              getValue(I.getOperand(1))));
3013     return 0;
3014   case Intrinsic::cos:
3015     setValue(&I, DAG.getNode(ISD::FCOS,
3016                              getValue(I.getOperand(1)).getValueType(),
3017                              getValue(I.getOperand(1))));
3018     return 0;
3019   case Intrinsic::log:
3020     setValue(&I, DAG.getNode(ISD::FLOG,
3021                              getValue(I.getOperand(1)).getValueType(),
3022                              getValue(I.getOperand(1))));
3023     return 0;
3024   case Intrinsic::log2:
3025     setValue(&I, DAG.getNode(ISD::FLOG2,
3026                              getValue(I.getOperand(1)).getValueType(),
3027                              getValue(I.getOperand(1))));
3028     return 0;
3029   case Intrinsic::log10:
3030     setValue(&I, DAG.getNode(ISD::FLOG10,
3031                              getValue(I.getOperand(1)).getValueType(),
3032                              getValue(I.getOperand(1))));
3033     return 0;
3034   case Intrinsic::exp:
3035     setValue(&I, DAG.getNode(ISD::FEXP,
3036                              getValue(I.getOperand(1)).getValueType(),
3037                              getValue(I.getOperand(1))));
3038     return 0;
3039   case Intrinsic::exp2:
3040     setValue(&I, DAG.getNode(ISD::FEXP2,
3041                              getValue(I.getOperand(1)).getValueType(),
3042                              getValue(I.getOperand(1))));
3043     return 0;
3044   case Intrinsic::pow:
3045     setValue(&I, DAG.getNode(ISD::FPOW,
3046                              getValue(I.getOperand(1)).getValueType(),
3047                              getValue(I.getOperand(1)),
3048                              getValue(I.getOperand(2))));
3049     return 0;
3050   case Intrinsic::pcmarker: {
3051     SDValue Tmp = getValue(I.getOperand(1));
3052     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3053     return 0;
3054   }
3055   case Intrinsic::readcyclecounter: {
3056     SDValue Op = getRoot();
3057     SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3058                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3059                                 &Op, 1);
3060     setValue(&I, Tmp);
3061     DAG.setRoot(Tmp.getValue(1));
3062     return 0;
3063   }
3064   case Intrinsic::part_select: {
3065     // Currently not implemented: just abort
3066     assert(0 && "part_select intrinsic not implemented");
3067     abort();
3068   }
3069   case Intrinsic::part_set: {
3070     // Currently not implemented: just abort
3071     assert(0 && "part_set intrinsic not implemented");
3072     abort();
3073   }
3074   case Intrinsic::bswap:
3075     setValue(&I, DAG.getNode(ISD::BSWAP,
3076                              getValue(I.getOperand(1)).getValueType(),
3077                              getValue(I.getOperand(1))));
3078     return 0;
3079   case Intrinsic::cttz: {
3080     SDValue Arg = getValue(I.getOperand(1));
3081     MVT Ty = Arg.getValueType();
3082     SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3083     setValue(&I, result);
3084     return 0;
3085   }
3086   case Intrinsic::ctlz: {
3087     SDValue Arg = getValue(I.getOperand(1));
3088     MVT Ty = Arg.getValueType();
3089     SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3090     setValue(&I, result);
3091     return 0;
3092   }
3093   case Intrinsic::ctpop: {
3094     SDValue Arg = getValue(I.getOperand(1));
3095     MVT Ty = Arg.getValueType();
3096     SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3097     setValue(&I, result);
3098     return 0;
3099   }
3100   case Intrinsic::stacksave: {
3101     SDValue Op = getRoot();
3102     SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3103               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3104     setValue(&I, Tmp);
3105     DAG.setRoot(Tmp.getValue(1));
3106     return 0;
3107   }
3108   case Intrinsic::stackrestore: {
3109     SDValue Tmp = getValue(I.getOperand(1));
3110     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3111     return 0;
3112   }
3113   case Intrinsic::var_annotation:
3114     // Discard annotate attributes
3115     return 0;
3116
3117   case Intrinsic::init_trampoline: {
3118     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3119
3120     SDValue Ops[6];
3121     Ops[0] = getRoot();
3122     Ops[1] = getValue(I.getOperand(1));
3123     Ops[2] = getValue(I.getOperand(2));
3124     Ops[3] = getValue(I.getOperand(3));
3125     Ops[4] = DAG.getSrcValue(I.getOperand(1));
3126     Ops[5] = DAG.getSrcValue(F);
3127
3128     SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3129                                 DAG.getNodeValueTypes(TLI.getPointerTy(),
3130                                                       MVT::Other), 2,
3131                                 Ops, 6);
3132
3133     setValue(&I, Tmp);
3134     DAG.setRoot(Tmp.getValue(1));
3135     return 0;
3136   }
3137
3138   case Intrinsic::gcroot:
3139     if (GFI) {
3140       Value *Alloca = I.getOperand(1);
3141       Constant *TypeMap = cast<Constant>(I.getOperand(2));
3142       
3143       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3144       GFI->addStackRoot(FI->getIndex(), TypeMap);
3145     }
3146     return 0;
3147
3148   case Intrinsic::gcread:
3149   case Intrinsic::gcwrite:
3150     assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3151     return 0;
3152
3153   case Intrinsic::flt_rounds: {
3154     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3155     return 0;
3156   }
3157
3158   case Intrinsic::trap: {
3159     DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3160     return 0;
3161   }
3162   case Intrinsic::prefetch: {
3163     SDValue Ops[4];
3164     Ops[0] = getRoot();
3165     Ops[1] = getValue(I.getOperand(1));
3166     Ops[2] = getValue(I.getOperand(2));
3167     Ops[3] = getValue(I.getOperand(3));
3168     DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3169     return 0;
3170   }
3171   
3172   case Intrinsic::memory_barrier: {
3173     SDValue Ops[6];
3174     Ops[0] = getRoot();
3175     for (int x = 1; x < 6; ++x)
3176       Ops[x] = getValue(I.getOperand(x));
3177
3178     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3179     return 0;
3180   }
3181   case Intrinsic::atomic_cmp_swap: {
3182     SDValue Root = getRoot();   
3183     SDValue L;
3184     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3185       case MVT::i8:
3186         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root, 
3187                           getValue(I.getOperand(1)), 
3188                           getValue(I.getOperand(2)),
3189                           getValue(I.getOperand(3)),
3190                           I.getOperand(1));
3191         break;
3192       case MVT::i16:
3193         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root, 
3194                           getValue(I.getOperand(1)), 
3195                           getValue(I.getOperand(2)),
3196                           getValue(I.getOperand(3)),
3197                           I.getOperand(1));
3198         break;
3199       case MVT::i32:
3200         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root, 
3201                           getValue(I.getOperand(1)), 
3202                           getValue(I.getOperand(2)),
3203                           getValue(I.getOperand(3)),
3204                           I.getOperand(1));
3205         break;
3206       case MVT::i64:
3207         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root, 
3208                           getValue(I.getOperand(1)), 
3209                           getValue(I.getOperand(2)),
3210                           getValue(I.getOperand(3)),
3211                           I.getOperand(1));
3212         break;
3213       default:
3214        assert(0 && "Invalid atomic type");
3215        abort();
3216     }
3217     setValue(&I, L);
3218     DAG.setRoot(L.getValue(1));
3219     return 0;
3220   }
3221   case Intrinsic::atomic_load_add:
3222     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3223       case MVT::i8:
3224         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3225       case MVT::i16:
3226         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3227       case MVT::i32:
3228         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3229       case MVT::i64:
3230         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3231       default:
3232        assert(0 && "Invalid atomic type");
3233        abort();
3234     }
3235   case Intrinsic::atomic_load_sub:
3236     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3237       case MVT::i8:
3238         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3239       case MVT::i16:
3240         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3241       case MVT::i32:
3242         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3243       case MVT::i64:
3244         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3245       default:
3246        assert(0 && "Invalid atomic type");
3247        abort();
3248     }
3249   case Intrinsic::atomic_load_or:
3250     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3251       case MVT::i8:
3252         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3253       case MVT::i16:
3254         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3255       case MVT::i32:
3256         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3257       case MVT::i64:
3258         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3259       default:
3260        assert(0 && "Invalid atomic type");
3261        abort();
3262     }
3263   case Intrinsic::atomic_load_xor:
3264     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3265       case MVT::i8:
3266         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3267       case MVT::i16:
3268         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3269       case MVT::i32:
3270         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3271       case MVT::i64:
3272         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3273       default:
3274        assert(0 && "Invalid atomic type");
3275        abort();
3276     }
3277   case Intrinsic::atomic_load_and:
3278     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3279       case MVT::i8:
3280         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3281       case MVT::i16:
3282         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3283       case MVT::i32:
3284         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3285       case MVT::i64:
3286         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3287       default:
3288        assert(0 && "Invalid atomic type");
3289        abort();
3290     }
3291   case Intrinsic::atomic_load_nand:
3292     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3293       case MVT::i8:
3294         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3295       case MVT::i16:
3296         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3297       case MVT::i32:
3298         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3299       case MVT::i64:
3300         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3301       default:
3302        assert(0 && "Invalid atomic type");
3303        abort();
3304     }
3305   case Intrinsic::atomic_load_max:
3306     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3307       case MVT::i8:
3308         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3309       case MVT::i16:
3310         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3311       case MVT::i32:
3312         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3313       case MVT::i64:
3314         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3315       default:
3316        assert(0 && "Invalid atomic type");
3317        abort();
3318     }
3319   case Intrinsic::atomic_load_min:
3320     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3321       case MVT::i8:
3322         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3323       case MVT::i16:
3324         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3325       case MVT::i32:
3326         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3327       case MVT::i64:
3328         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3329       default:
3330        assert(0 && "Invalid atomic type");
3331        abort();
3332     }
3333   case Intrinsic::atomic_load_umin:
3334     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3335       case MVT::i8:
3336         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
3337       case MVT::i16:
3338         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
3339       case MVT::i32:
3340         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
3341       case MVT::i64:
3342         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
3343       default:
3344        assert(0 && "Invalid atomic type");
3345        abort();
3346     }
3347   case Intrinsic::atomic_load_umax:
3348     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3349       case MVT::i8:
3350         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
3351       case MVT::i16:
3352         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
3353       case MVT::i32:
3354         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
3355       case MVT::i64:
3356         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
3357       default:
3358        assert(0 && "Invalid atomic type");
3359        abort();
3360     }
3361   case Intrinsic::atomic_swap:
3362     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3363       case MVT::i8:
3364         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
3365       case MVT::i16:
3366         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
3367       case MVT::i32:
3368         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
3369       case MVT::i64:
3370         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
3371       default:
3372        assert(0 && "Invalid atomic type");
3373        abort();
3374     }
3375   }
3376 }
3377
3378
3379 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
3380                                        bool IsTailCall,
3381                                        MachineBasicBlock *LandingPad) {
3382   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3383   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3384   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3385   unsigned BeginLabel = 0, EndLabel = 0;
3386
3387   TargetLowering::ArgListTy Args;
3388   TargetLowering::ArgListEntry Entry;
3389   Args.reserve(CS.arg_size());
3390   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3391        i != e; ++i) {
3392     SDValue ArgNode = getValue(*i);
3393     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3394
3395     unsigned attrInd = i - CS.arg_begin() + 1;
3396     Entry.isSExt  = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3397     Entry.isZExt  = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3398     Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3399     Entry.isSRet  = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3400     Entry.isNest  = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3401     Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3402     Entry.Alignment = CS.getParamAlignment(attrInd);
3403     Args.push_back(Entry);
3404   }
3405
3406   if (LandingPad && MMI) {
3407     // Insert a label before the invoke call to mark the try range.  This can be
3408     // used to detect deletion of the invoke via the MachineModuleInfo.
3409     BeginLabel = MMI->NextLabelID();
3410     // Both PendingLoads and PendingExports must be flushed here;
3411     // this call might not return.
3412     (void)getRoot();
3413     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
3414   }
3415
3416   std::pair<SDValue,SDValue> Result =
3417     TLI.LowerCallTo(getRoot(), CS.getType(),
3418                     CS.paramHasAttr(0, ParamAttr::SExt),
3419                     CS.paramHasAttr(0, ParamAttr::ZExt),
3420                     FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3421                     Callee, Args, DAG);
3422   if (CS.getType() != Type::VoidTy)
3423     setValue(CS.getInstruction(), Result.first);
3424   DAG.setRoot(Result.second);
3425
3426   if (LandingPad && MMI) {
3427     // Insert a label at the end of the invoke call to mark the try range.  This
3428     // can be used to detect deletion of the invoke via the MachineModuleInfo.
3429     EndLabel = MMI->NextLabelID();
3430     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
3431
3432     // Inform MachineModuleInfo of range.
3433     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3434   }
3435 }
3436
3437
3438 void SelectionDAGLowering::visitCall(CallInst &I) {
3439   const char *RenameFn = 0;
3440   if (Function *F = I.getCalledFunction()) {
3441     if (F->isDeclaration()) {
3442       if (unsigned IID = F->getIntrinsicID()) {
3443         RenameFn = visitIntrinsicCall(I, IID);
3444         if (!RenameFn)
3445           return;
3446       }
3447     }
3448
3449     // Check for well-known libc/libm calls.  If the function is internal, it
3450     // can't be a library call.
3451     unsigned NameLen = F->getNameLen();
3452     if (!F->hasInternalLinkage() && NameLen) {
3453       const char *NameStr = F->getNameStart();
3454       if (NameStr[0] == 'c' &&
3455           ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3456            (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3457         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
3458             I.getOperand(1)->getType()->isFloatingPoint() &&
3459             I.getType() == I.getOperand(1)->getType() &&
3460             I.getType() == I.getOperand(2)->getType()) {
3461           SDValue LHS = getValue(I.getOperand(1));
3462           SDValue RHS = getValue(I.getOperand(2));
3463           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3464                                    LHS, RHS));
3465           return;
3466         }
3467       } else if (NameStr[0] == 'f' &&
3468                  ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3469                   (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3470                   (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3471         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3472             I.getOperand(1)->getType()->isFloatingPoint() &&
3473             I.getType() == I.getOperand(1)->getType()) {
3474           SDValue Tmp = getValue(I.getOperand(1));
3475           setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3476           return;
3477         }
3478       } else if (NameStr[0] == 's' && 
3479                  ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3480                   (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3481                   (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3482         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3483             I.getOperand(1)->getType()->isFloatingPoint() &&
3484             I.getType() == I.getOperand(1)->getType()) {
3485           SDValue Tmp = getValue(I.getOperand(1));
3486           setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3487           return;
3488         }
3489       } else if (NameStr[0] == 'c' &&
3490                  ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3491                   (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3492                   (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3493         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3494             I.getOperand(1)->getType()->isFloatingPoint() &&
3495             I.getType() == I.getOperand(1)->getType()) {
3496           SDValue Tmp = getValue(I.getOperand(1));
3497           setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3498           return;
3499         }
3500       }
3501     }
3502   } else if (isa<InlineAsm>(I.getOperand(0))) {
3503     visitInlineAsm(&I);
3504     return;
3505   }
3506
3507   SDValue Callee;
3508   if (!RenameFn)
3509     Callee = getValue(I.getOperand(0));
3510   else
3511     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3512
3513   LowerCallTo(&I, Callee, I.isTailCall());
3514 }
3515
3516
3517 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3518 /// this value and returns the result as a ValueVT value.  This uses 
3519 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3520 /// If the Flag pointer is NULL, no flag is used.
3521 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 
3522                                       SDValue &Chain,
3523                                       SDValue *Flag) const {
3524   // Assemble the legal parts into the final values.
3525   SmallVector<SDValue, 4> Values(ValueVTs.size());
3526   SmallVector<SDValue, 8> Parts;
3527   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3528     // Copy the legal parts from the registers.
3529     MVT ValueVT = ValueVTs[Value];
3530     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3531     MVT RegisterVT = RegVTs[Value];
3532
3533     Parts.resize(NumRegs);
3534     for (unsigned i = 0; i != NumRegs; ++i) {
3535       SDValue P;
3536       if (Flag == 0)
3537         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3538       else {
3539         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3540         *Flag = P.getValue(2);
3541       }
3542       Chain = P.getValue(1);
3543       
3544       // If the source register was virtual and if we know something about it,
3545       // add an assert node.
3546       if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3547           RegisterVT.isInteger() && !RegisterVT.isVector()) {
3548         unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3549         FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3550         if (FLI.LiveOutRegInfo.size() > SlotNo) {
3551           FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3552           
3553           unsigned RegSize = RegisterVT.getSizeInBits();
3554           unsigned NumSignBits = LOI.NumSignBits;
3555           unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3556           
3557           // FIXME: We capture more information than the dag can represent.  For
3558           // now, just use the tightest assertzext/assertsext possible.
3559           bool isSExt = true;
3560           MVT FromVT(MVT::Other);
3561           if (NumSignBits == RegSize)
3562             isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
3563           else if (NumZeroBits >= RegSize-1)
3564             isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
3565           else if (NumSignBits > RegSize-8)
3566             isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
3567           else if (NumZeroBits >= RegSize-9)
3568             isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
3569           else if (NumSignBits > RegSize-16)
3570             isSExt = true, FromVT = MVT::i16;   // ASSERT SEXT 16
3571           else if (NumZeroBits >= RegSize-17)
3572             isSExt = false, FromVT = MVT::i16;  // ASSERT ZEXT 16
3573           else if (NumSignBits > RegSize-32)
3574             isSExt = true, FromVT = MVT::i32;   // ASSERT SEXT 32
3575           else if (NumZeroBits >= RegSize-33)
3576             isSExt = false, FromVT = MVT::i32;  // ASSERT ZEXT 32
3577           
3578           if (FromVT != MVT::Other) {
3579             P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3580                             RegisterVT, P, DAG.getValueType(FromVT));
3581
3582           }
3583         }
3584       }
3585       
3586       Parts[i] = P;
3587     }
3588   
3589     Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
3590                                      ValueVT);
3591     Part += NumRegs;
3592     Parts.clear();
3593   }
3594
3595   return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3596                             &Values[0], ValueVTs.size());
3597 }
3598
3599 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3600 /// specified value into the registers specified by this object.  This uses 
3601 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3602 /// If the Flag pointer is NULL, no flag is used.
3603 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3604                                  SDValue &Chain, SDValue *Flag) const {
3605   // Get the list of the values's legal parts.
3606   unsigned NumRegs = Regs.size();
3607   SmallVector<SDValue, 8> Parts(NumRegs);
3608   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3609     MVT ValueVT = ValueVTs[Value];
3610     unsigned NumParts = TLI->getNumRegisters(ValueVT);
3611     MVT RegisterVT = RegVTs[Value];
3612
3613     getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
3614                    &Parts[Part], NumParts, RegisterVT);
3615     Part += NumParts;
3616   }
3617
3618   // Copy the parts into the registers.
3619   SmallVector<SDValue, 8> Chains(NumRegs);
3620   for (unsigned i = 0; i != NumRegs; ++i) {
3621     SDValue Part;
3622     if (Flag == 0)
3623       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3624     else {
3625       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3626       *Flag = Part.getValue(1);
3627     }
3628     Chains[i] = Part.getValue(0);
3629   }
3630   
3631   if (NumRegs == 1 || Flag)
3632     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 
3633     // flagged to it. That is the CopyToReg nodes and the user are considered
3634     // a single scheduling unit. If we create a TokenFactor and return it as
3635     // chain, then the TokenFactor is both a predecessor (operand) of the
3636     // user as well as a successor (the TF operands are flagged to the user).
3637     // c1, f1 = CopyToReg
3638     // c2, f2 = CopyToReg
3639     // c3     = TokenFactor c1, c2
3640     // ...
3641     //        = op c3, ..., f2
3642     Chain = Chains[NumRegs-1];
3643   else
3644     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3645 }
3646
3647 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3648 /// operand list.  This adds the code marker and includes the number of 
3649 /// values added into it.
3650 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3651                                         std::vector<SDValue> &Ops) const {
3652   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3653   Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3654   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3655     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3656     MVT RegisterVT = RegVTs[Value];
3657     for (unsigned i = 0; i != NumRegs; ++i)
3658       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3659   }
3660 }
3661
3662 /// isAllocatableRegister - If the specified register is safe to allocate, 
3663 /// i.e. it isn't a stack pointer or some other special register, return the
3664 /// register class for the register.  Otherwise, return null.
3665 static const TargetRegisterClass *
3666 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3667                       const TargetLowering &TLI,
3668                       const TargetRegisterInfo *TRI) {
3669   MVT FoundVT = MVT::Other;
3670   const TargetRegisterClass *FoundRC = 0;
3671   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3672        E = TRI->regclass_end(); RCI != E; ++RCI) {
3673     MVT ThisVT = MVT::Other;
3674
3675     const TargetRegisterClass *RC = *RCI;
3676     // If none of the the value types for this register class are valid, we 
3677     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
3678     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3679          I != E; ++I) {
3680       if (TLI.isTypeLegal(*I)) {
3681         // If we have already found this register in a different register class,
3682         // choose the one with the largest VT specified.  For example, on
3683         // PowerPC, we favor f64 register classes over f32.
3684         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3685           ThisVT = *I;
3686           break;
3687         }
3688       }
3689     }
3690     
3691     if (ThisVT == MVT::Other) continue;
3692     
3693     // NOTE: This isn't ideal.  In particular, this might allocate the
3694     // frame pointer in functions that need it (due to them not being taken
3695     // out of allocation, because a variable sized allocation hasn't been seen
3696     // yet).  This is a slight code pessimization, but should still work.
3697     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3698          E = RC->allocation_order_end(MF); I != E; ++I)
3699       if (*I == Reg) {
3700         // We found a matching register class.  Keep looking at others in case
3701         // we find one with larger registers that this physreg is also in.
3702         FoundRC = RC;
3703         FoundVT = ThisVT;
3704         break;
3705       }
3706   }
3707   return FoundRC;
3708 }    
3709
3710
3711 namespace llvm {
3712 /// AsmOperandInfo - This contains information for each constraint that we are
3713 /// lowering.
3714 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3715   /// CallOperand - If this is the result output operand or a clobber
3716   /// this is null, otherwise it is the incoming operand to the CallInst.
3717   /// This gets modified as the asm is processed.
3718   SDValue CallOperand;
3719
3720   /// AssignedRegs - If this is a register or register class operand, this
3721   /// contains the set of register corresponding to the operand.
3722   RegsForValue AssignedRegs;
3723   
3724   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3725     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3726   }
3727   
3728   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3729   /// busy in OutputRegs/InputRegs.
3730   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3731                          std::set<unsigned> &OutputRegs, 
3732                          std::set<unsigned> &InputRegs,
3733                          const TargetRegisterInfo &TRI) const {
3734     if (isOutReg) {
3735       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3736         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3737     }
3738     if (isInReg) {
3739       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3740         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3741     }
3742   }
3743   
3744 private:
3745   /// MarkRegAndAliases - Mark the specified register and all aliases in the
3746   /// specified set.
3747   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 
3748                                 const TargetRegisterInfo &TRI) {
3749     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3750     Regs.insert(Reg);
3751     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3752       for (; *Aliases; ++Aliases)
3753         Regs.insert(*Aliases);
3754   }
3755 };
3756 } // end llvm namespace.
3757
3758
3759 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3760 /// specified operand.  We prefer to assign virtual registers, to allow the
3761 /// register allocator handle the assignment process.  However, if the asm uses
3762 /// features that we can't model on machineinstrs, we have SDISel do the
3763 /// allocation.  This produces generally horrible, but correct, code.
3764 ///
3765 ///   OpInfo describes the operand.
3766 ///   HasEarlyClobber is true if there are any early clobber constraints (=&r)
3767 ///     or any explicitly clobbered registers.
3768 ///   Input and OutputRegs are the set of already allocated physical registers.
3769 ///
3770 void SelectionDAGLowering::
3771 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3772                      std::set<unsigned> &OutputRegs, 
3773                      std::set<unsigned> &InputRegs) {
3774   // Compute whether this value requires an input register, an output register,
3775   // or both.
3776   bool isOutReg = false;
3777   bool isInReg = false;
3778   switch (OpInfo.Type) {
3779   case InlineAsm::isOutput:
3780     isOutReg = true;
3781     
3782     // If this is an early-clobber output, or if there is an input
3783     // constraint that matches this, we need to reserve the input register
3784     // so no other inputs allocate to it.
3785     isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3786     break;
3787   case InlineAsm::isInput:
3788     isInReg = true;
3789     isOutReg = false;
3790     break;
3791   case InlineAsm::isClobber:
3792     isOutReg = true;
3793     isInReg = true;
3794     break;
3795   }
3796   
3797   
3798   MachineFunction &MF = DAG.getMachineFunction();
3799   SmallVector<unsigned, 4> Regs;
3800   
3801   // If this is a constraint for a single physreg, or a constraint for a
3802   // register class, find it.
3803   std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
3804     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3805                                      OpInfo.ConstraintVT);
3806
3807   unsigned NumRegs = 1;
3808   if (OpInfo.ConstraintVT != MVT::Other)
3809     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3810   MVT RegVT;
3811   MVT ValueVT = OpInfo.ConstraintVT;
3812   
3813
3814   // If this is a constraint for a specific physical register, like {r17},
3815   // assign it now.
3816   if (PhysReg.first) {
3817     if (OpInfo.ConstraintVT == MVT::Other)
3818       ValueVT = *PhysReg.second->vt_begin();
3819     
3820     // Get the actual register value type.  This is important, because the user
3821     // may have asked for (e.g.) the AX register in i32 type.  We need to
3822     // remember that AX is actually i16 to get the right extension.
3823     RegVT = *PhysReg.second->vt_begin();
3824     
3825     // This is a explicit reference to a physical register.
3826     Regs.push_back(PhysReg.first);
3827
3828     // If this is an expanded reference, add the rest of the regs to Regs.
3829     if (NumRegs != 1) {
3830       TargetRegisterClass::iterator I = PhysReg.second->begin();
3831       for (; *I != PhysReg.first; ++I)
3832         assert(I != PhysReg.second->end() && "Didn't find reg!"); 
3833       
3834       // Already added the first reg.
3835       --NumRegs; ++I;
3836       for (; NumRegs; --NumRegs, ++I) {
3837         assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
3838         Regs.push_back(*I);
3839       }
3840     }
3841     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3842     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3843     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3844     return;
3845   }
3846   
3847   // Otherwise, if this was a reference to an LLVM register class, create vregs
3848   // for this reference.
3849   std::vector<unsigned> RegClassRegs;
3850   const TargetRegisterClass *RC = PhysReg.second;
3851   if (RC) {
3852     // If this is an early clobber or tied register, our regalloc doesn't know
3853     // how to maintain the constraint.  If it isn't, go ahead and create vreg
3854     // and let the regalloc do the right thing.
3855     if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3856         // If there is some other early clobber and this is an input register,
3857         // then we are forced to pre-allocate the input reg so it doesn't
3858         // conflict with the earlyclobber.
3859         !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3860       RegVT = *PhysReg.second->vt_begin();
3861       
3862       if (OpInfo.ConstraintVT == MVT::Other)
3863         ValueVT = RegVT;
3864
3865       // Create the appropriate number of virtual registers.
3866       MachineRegisterInfo &RegInfo = MF.getRegInfo();
3867       for (; NumRegs; --NumRegs)
3868         Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3869       
3870       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3871       return;
3872     }
3873     
3874     // Otherwise, we can't allocate it.  Let the code below figure out how to
3875     // maintain these constraints.
3876     RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3877     
3878   } else {
3879     // This is a reference to a register class that doesn't directly correspond
3880     // to an LLVM register class.  Allocate NumRegs consecutive, available,
3881     // registers from the class.
3882     RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3883                                                          OpInfo.ConstraintVT);
3884   }
3885   
3886   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3887   unsigned NumAllocated = 0;
3888   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3889     unsigned Reg = RegClassRegs[i];
3890     // See if this register is available.
3891     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
3892         (isInReg  && InputRegs.count(Reg))) {    // Already used.
3893       // Make sure we find consecutive registers.
3894       NumAllocated = 0;
3895       continue;
3896     }
3897     
3898     // Check to see if this register is allocatable (i.e. don't give out the
3899     // stack pointer).
3900     if (RC == 0) {
3901       RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3902       if (!RC) {        // Couldn't allocate this register.
3903         // Reset NumAllocated to make sure we return consecutive registers.
3904         NumAllocated = 0;
3905         continue;
3906       }
3907     }
3908     
3909     // Okay, this register is good, we can use it.
3910     ++NumAllocated;
3911
3912     // If we allocated enough consecutive registers, succeed.
3913     if (NumAllocated == NumRegs) {
3914       unsigned RegStart = (i-NumAllocated)+1;
3915       unsigned RegEnd   = i+1;
3916       // Mark all of the allocated registers used.
3917       for (unsigned i = RegStart; i != RegEnd; ++i)
3918         Regs.push_back(RegClassRegs[i]);
3919       
3920       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(), 
3921                                          OpInfo.ConstraintVT);
3922       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3923       return;
3924     }
3925   }
3926   
3927   // Otherwise, we couldn't allocate enough registers for this.
3928 }
3929
3930
3931 /// visitInlineAsm - Handle a call to an InlineAsm object.
3932 ///
3933 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3934   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3935
3936   /// ConstraintOperands - Information about all of the constraints.
3937   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3938   
3939   SDValue Chain = getRoot();
3940   SDValue Flag;
3941   
3942   std::set<unsigned> OutputRegs, InputRegs;
3943
3944   // Do a prepass over the constraints, canonicalizing them, and building up the
3945   // ConstraintOperands list.
3946   std::vector<InlineAsm::ConstraintInfo>
3947     ConstraintInfos = IA->ParseConstraints();
3948
3949   // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3950   // constraint.  If so, we can't let the register allocator allocate any input
3951   // registers, because it will not know to avoid the earlyclobbered output reg.
3952   bool SawEarlyClobber = false;
3953   
3954   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
3955   unsigned ResNo = 0;   // ResNo - The result number of the next output.
3956   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3957     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3958     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3959     
3960     MVT OpVT = MVT::Other;
3961
3962     // Compute the value type for each operand.
3963     switch (OpInfo.Type) {
3964     case InlineAsm::isOutput:
3965       // Indirect outputs just consume an argument.
3966       if (OpInfo.isIndirect) {
3967         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3968         break;
3969       }
3970       // The return value of the call is this value.  As such, there is no
3971       // corresponding argument.
3972       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3973       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3974         OpVT = TLI.getValueType(STy->getElementType(ResNo));
3975       } else {
3976         assert(ResNo == 0 && "Asm only has one result!");
3977         OpVT = TLI.getValueType(CS.getType());
3978       }
3979       ++ResNo;
3980       break;
3981     case InlineAsm::isInput:
3982       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3983       break;
3984     case InlineAsm::isClobber:
3985       // Nothing to do.
3986       break;
3987     }
3988
3989     // If this is an input or an indirect output, process the call argument.
3990     // BasicBlocks are labels, currently appearing only in asm's.
3991     if (OpInfo.CallOperandVal) {
3992       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3993         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3994       else {
3995         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3996         const Type *OpTy = OpInfo.CallOperandVal->getType();
3997         // If this is an indirect operand, the operand is a pointer to the
3998         // accessed type.
3999         if (OpInfo.isIndirect)
4000           OpTy = cast<PointerType>(OpTy)->getElementType();
4001
4002         // If OpTy is not a single value, it may be a struct/union that we
4003         // can tile with integers.
4004         if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4005           unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4006           switch (BitSize) {
4007           default: break;
4008           case 1:
4009           case 8:
4010           case 16:
4011           case 32:
4012           case 64:
4013             OpTy = IntegerType::get(BitSize);
4014             break;
4015           }
4016         }
4017
4018         OpVT = TLI.getValueType(OpTy, true);
4019       }
4020     }
4021     
4022     OpInfo.ConstraintVT = OpVT;
4023     
4024     // Compute the constraint code and ConstraintType to use.
4025     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4026
4027     // Keep track of whether we see an earlyclobber.
4028     SawEarlyClobber |= OpInfo.isEarlyClobber;
4029     
4030     // If we see a clobber of a register, it is an early clobber.
4031     if (!SawEarlyClobber &&
4032         OpInfo.Type == InlineAsm::isClobber &&
4033         OpInfo.ConstraintType == TargetLowering::C_Register) {
4034       // Note that we want to ignore things that we don't track here, like
4035       // dirflag, fpsr, flags, etc.
4036       std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
4037         TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4038                                          OpInfo.ConstraintVT);
4039       if (PhysReg.first || PhysReg.second) {
4040         // This is a register we know of.
4041         SawEarlyClobber = true;
4042       }
4043     }
4044     
4045     // If this is a memory input, and if the operand is not indirect, do what we
4046     // need to to provide an address for the memory input.
4047     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4048         !OpInfo.isIndirect) {
4049       assert(OpInfo.Type == InlineAsm::isInput &&
4050              "Can only indirectify direct input operands!");
4051       
4052       // Memory operands really want the address of the value.  If we don't have
4053       // an indirect input, put it in the constpool if we can, otherwise spill
4054       // it to a stack slot.
4055       
4056       // If the operand is a float, integer, or vector constant, spill to a
4057       // constant pool entry to get its address.
4058       Value *OpVal = OpInfo.CallOperandVal;
4059       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4060           isa<ConstantVector>(OpVal)) {
4061         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4062                                                  TLI.getPointerTy());
4063       } else {
4064         // Otherwise, create a stack slot and emit a store to it before the
4065         // asm.
4066         const Type *Ty = OpVal->getType();
4067         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4068         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4069         MachineFunction &MF = DAG.getMachineFunction();
4070         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4071         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4072         Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4073         OpInfo.CallOperand = StackSlot;
4074       }
4075      
4076       // There is no longer a Value* corresponding to this operand.
4077       OpInfo.CallOperandVal = 0;
4078       // It is now an indirect operand.
4079       OpInfo.isIndirect = true;
4080     }
4081     
4082     // If this constraint is for a specific register, allocate it before
4083     // anything else.
4084     if (OpInfo.ConstraintType == TargetLowering::C_Register)
4085       GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4086   }
4087   ConstraintInfos.clear();
4088   
4089   
4090   // Second pass - Loop over all of the operands, assigning virtual or physregs
4091   // to registerclass operands.
4092   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4093     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4094     
4095     // C_Register operands have already been allocated, Other/Memory don't need
4096     // to be.
4097     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4098       GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4099   }    
4100   
4101   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4102   std::vector<SDValue> AsmNodeOperands;
4103   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
4104   AsmNodeOperands.push_back(
4105           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4106   
4107   
4108   // Loop over all of the inputs, copying the operand values into the
4109   // appropriate registers and processing the output regs.
4110   RegsForValue RetValRegs;
4111  
4112   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4113   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4114   
4115   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4116     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4117
4118     switch (OpInfo.Type) {
4119     case InlineAsm::isOutput: {
4120       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4121           OpInfo.ConstraintType != TargetLowering::C_Register) {
4122         // Memory output, or 'other' output (e.g. 'X' constraint).
4123         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4124
4125         // Add information to the INLINEASM node to know about this output.
4126         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4127         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 
4128                                                         TLI.getPointerTy()));
4129         AsmNodeOperands.push_back(OpInfo.CallOperand);
4130         break;
4131       }
4132
4133       // Otherwise, this is a register or register class output.
4134
4135       // Copy the output from the appropriate register.  Find a register that
4136       // we can use.
4137       if (OpInfo.AssignedRegs.Regs.empty()) {
4138         cerr << "Couldn't allocate output reg for constraint '"
4139              << OpInfo.ConstraintCode << "'!\n";
4140         exit(1);
4141       }
4142
4143       // If this is an indirect operand, store through the pointer after the
4144       // asm.
4145       if (OpInfo.isIndirect) {
4146         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4147                                                       OpInfo.CallOperandVal));
4148       } else {
4149         // This is the result value of the call.
4150         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4151         // Concatenate this output onto the outputs list.
4152         RetValRegs.append(OpInfo.AssignedRegs);
4153       }
4154       
4155       // Add information to the INLINEASM node to know that this register is
4156       // set.
4157       OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4158                                                AsmNodeOperands);
4159       break;
4160     }
4161     case InlineAsm::isInput: {
4162       SDValue InOperandVal = OpInfo.CallOperand;
4163       
4164       if (isdigit(OpInfo.ConstraintCode[0])) {    // Matching constraint?
4165         // If this is required to match an output register we have already set,
4166         // just use its register.
4167         unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4168         
4169         // Scan until we find the definition we already emitted of this operand.
4170         // When we find it, create a RegsForValue operand.
4171         unsigned CurOp = 2;  // The first operand.
4172         for (; OperandNo; --OperandNo) {
4173           // Advance to the next operand.
4174           unsigned NumOps = 
4175             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4176           assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4177                   (NumOps & 7) == 4 /*MEM*/) &&
4178                  "Skipped past definitions?");
4179           CurOp += (NumOps>>3)+1;
4180         }
4181
4182         unsigned NumOps = 
4183           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4184         if ((NumOps & 7) == 2 /*REGDEF*/) {
4185           // Add NumOps>>3 registers to MatchedRegs.
4186           RegsForValue MatchedRegs;
4187           MatchedRegs.TLI = &TLI;
4188           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4189           MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4190           for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4191             unsigned Reg =
4192               cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4193             MatchedRegs.Regs.push_back(Reg);
4194           }
4195         
4196           // Use the produced MatchedRegs object to 
4197           MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4198           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4199           break;
4200         } else {
4201           assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4202           assert((NumOps >> 3) == 1 && "Unexpected number of operands"); 
4203           // Add information to the INLINEASM node to know about this input.
4204           unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4205           AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4206                                                           TLI.getPointerTy()));
4207           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4208           break;
4209         }
4210       }
4211       
4212       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4213         assert(!OpInfo.isIndirect && 
4214                "Don't know how to handle indirect other inputs yet!");
4215         
4216         std::vector<SDValue> Ops;
4217         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4218                                          Ops, DAG);
4219         if (Ops.empty()) {
4220           cerr << "Invalid operand for inline asm constraint '"
4221                << OpInfo.ConstraintCode << "'!\n";
4222           exit(1);
4223         }
4224         
4225         // Add information to the INLINEASM node to know about this input.
4226         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4227         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 
4228                                                         TLI.getPointerTy()));
4229         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4230         break;
4231       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4232         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4233         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4234                "Memory operands expect pointer values");
4235                
4236         // Add information to the INLINEASM node to know about this input.
4237         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4238         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4239                                                         TLI.getPointerTy()));
4240         AsmNodeOperands.push_back(InOperandVal);
4241         break;
4242       }
4243         
4244       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4245               OpInfo.ConstraintType == TargetLowering::C_Register) &&
4246              "Unknown constraint type!");
4247       assert(!OpInfo.isIndirect && 
4248              "Don't know how to handle indirect register inputs yet!");
4249
4250       // Copy the input into the appropriate registers.
4251       assert(!OpInfo.AssignedRegs.Regs.empty() &&
4252              "Couldn't allocate input reg!");
4253
4254       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4255       
4256       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4257                                                AsmNodeOperands);
4258       break;
4259     }
4260     case InlineAsm::isClobber: {
4261       // Add the clobbered value to the operand list, so that the register
4262       // allocator is aware that the physreg got clobbered.
4263       if (!OpInfo.AssignedRegs.Regs.empty())
4264         OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4265                                                  AsmNodeOperands);
4266       break;
4267     }
4268     }
4269   }
4270   
4271   // Finish up input operands.
4272   AsmNodeOperands[0] = Chain;
4273   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
4274   
4275   Chain = DAG.getNode(ISD::INLINEASM, 
4276                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4277                       &AsmNodeOperands[0], AsmNodeOperands.size());
4278   Flag = Chain.getValue(1);
4279
4280   // If this asm returns a register value, copy the result from that register
4281   // and set it as the value of the call.
4282   if (!RetValRegs.Regs.empty()) {
4283     SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4284
4285     // If any of the results of the inline asm is a vector, it may have the
4286     // wrong width/num elts.  This can happen for register classes that can
4287     // contain multiple different value types.  The preg or vreg allocated may
4288     // not have the same VT as was expected.  Convert it to the right type with
4289     // bit_convert.
4290     if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4291       for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4292         if (Val.getNode()->getValueType(i).isVector())
4293           Val = DAG.getNode(ISD::BIT_CONVERT,
4294                             TLI.getValueType(ResSTy->getElementType(i)), Val);
4295       }
4296     } else {
4297       if (Val.getValueType().isVector())
4298         Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4299                           Val);
4300     }
4301
4302     setValue(CS.getInstruction(), Val);
4303   }
4304   
4305   std::vector<std::pair<SDValue, Value*> > StoresToEmit;
4306   
4307   // Process indirect outputs, first output all of the flagged copies out of
4308   // physregs.
4309   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4310     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4311     Value *Ptr = IndirectStoresToEmit[i].second;
4312     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4313     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4314   }
4315   
4316   // Emit the non-flagged stores from the physregs.
4317   SmallVector<SDValue, 8> OutChains;
4318   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4319     OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4320                                     getValue(StoresToEmit[i].second),
4321                                     StoresToEmit[i].second, 0));
4322   if (!OutChains.empty())
4323     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4324                         &OutChains[0], OutChains.size());
4325   DAG.setRoot(Chain);
4326 }
4327
4328
4329 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4330   SDValue Src = getValue(I.getOperand(0));
4331
4332   MVT IntPtr = TLI.getPointerTy();
4333
4334   if (IntPtr.bitsLT(Src.getValueType()))
4335     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4336   else if (IntPtr.bitsGT(Src.getValueType()))
4337     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4338
4339   // Scale the source by the type size.
4340   uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4341   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4342                     Src, DAG.getIntPtrConstant(ElementSize));
4343
4344   TargetLowering::ArgListTy Args;
4345   TargetLowering::ArgListEntry Entry;
4346   Entry.Node = Src;
4347   Entry.Ty = TLI.getTargetData()->getIntPtrType();
4348   Args.push_back(Entry);
4349
4350   std::pair<SDValue,SDValue> Result =
4351     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4352                     true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4353   setValue(&I, Result.first);  // Pointers always fit in registers
4354   DAG.setRoot(Result.second);
4355 }
4356
4357 void SelectionDAGLowering::visitFree(FreeInst &I) {
4358   TargetLowering::ArgListTy Args;
4359   TargetLowering::ArgListEntry Entry;
4360   Entry.Node = getValue(I.getOperand(0));
4361   Entry.Ty = TLI.getTargetData()->getIntPtrType();
4362   Args.push_back(Entry);
4363   MVT IntPtr = TLI.getPointerTy();
4364   std::pair<SDValue,SDValue> Result =
4365     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4366                     CallingConv::C, true,
4367                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4368   DAG.setRoot(Result.second);
4369 }
4370
4371 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4372   DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 
4373                           getValue(I.getOperand(1)), 
4374                           DAG.getSrcValue(I.getOperand(1))));
4375 }
4376
4377 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4378   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4379                              getValue(I.getOperand(0)),
4380                              DAG.getSrcValue(I.getOperand(0)));
4381   setValue(&I, V);
4382   DAG.setRoot(V.getValue(1));
4383 }
4384
4385 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4386   DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4387                           getValue(I.getOperand(1)), 
4388                           DAG.getSrcValue(I.getOperand(1))));
4389 }
4390
4391 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4392   DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 
4393                           getValue(I.getOperand(1)), 
4394                           getValue(I.getOperand(2)),
4395                           DAG.getSrcValue(I.getOperand(1)),
4396                           DAG.getSrcValue(I.getOperand(2))));
4397 }
4398
4399 /// TargetLowering::LowerArguments - This is the default LowerArguments
4400 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
4401 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 
4402 /// integrated into SDISel.
4403 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
4404                                     SmallVectorImpl<SDValue> &ArgValues) {
4405   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4406   SmallVector<SDValue, 3+16> Ops;
4407   Ops.push_back(DAG.getRoot());
4408   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4409   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4410
4411   // Add one result value for each formal argument.
4412   SmallVector<MVT, 16> RetVals;
4413   unsigned j = 1;
4414   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4415        I != E; ++I, ++j) {
4416     SmallVector<MVT, 4> ValueVTs;
4417     ComputeValueVTs(*this, I->getType(), ValueVTs);
4418     for (unsigned Value = 0, NumValues = ValueVTs.size();
4419          Value != NumValues; ++Value) {
4420       MVT VT = ValueVTs[Value];
4421       const Type *ArgTy = VT.getTypeForMVT();
4422       ISD::ArgFlagsTy Flags;
4423       unsigned OriginalAlignment =
4424         getTargetData()->getABITypeAlignment(ArgTy);
4425
4426       if (F.paramHasAttr(j, ParamAttr::ZExt))
4427         Flags.setZExt();
4428       if (F.paramHasAttr(j, ParamAttr::SExt))
4429         Flags.setSExt();
4430       if (F.paramHasAttr(j, ParamAttr::InReg))
4431         Flags.setInReg();
4432       if (F.paramHasAttr(j, ParamAttr::StructRet))
4433         Flags.setSRet();
4434       if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4435         Flags.setByVal();
4436         const PointerType *Ty = cast<PointerType>(I->getType());
4437         const Type *ElementTy = Ty->getElementType();
4438         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4439         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
4440         // For ByVal, alignment should be passed from FE.  BE will guess if
4441         // this info is not there but there are cases it cannot get right.
4442         if (F.getParamAlignment(j))
4443           FrameAlign = F.getParamAlignment(j);
4444         Flags.setByValAlign(FrameAlign);
4445         Flags.setByValSize(FrameSize);
4446       }
4447       if (F.paramHasAttr(j, ParamAttr::Nest))
4448         Flags.setNest();
4449       Flags.setOrigAlign(OriginalAlignment);
4450
4451       MVT RegisterVT = getRegisterType(VT);
4452       unsigned NumRegs = getNumRegisters(VT);
4453       for (unsigned i = 0; i != NumRegs; ++i) {
4454         RetVals.push_back(RegisterVT);
4455         ISD::ArgFlagsTy MyFlags = Flags;
4456         if (NumRegs > 1 && i == 0)
4457           MyFlags.setSplit();
4458         // if it isn't first piece, alignment must be 1
4459         else if (i > 0)
4460           MyFlags.setOrigAlign(1);
4461         Ops.push_back(DAG.getArgFlags(MyFlags));
4462       }
4463     }
4464   }
4465
4466   RetVals.push_back(MVT::Other);
4467   
4468   // Create the node.
4469   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4470                                DAG.getVTList(&RetVals[0], RetVals.size()),
4471                                &Ops[0], Ops.size()).getNode();
4472   
4473   // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
4474   // allows exposing the loads that may be part of the argument access to the
4475   // first DAGCombiner pass.
4476   SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
4477   
4478   // The number of results should match up, except that the lowered one may have
4479   // an extra flag result.
4480   assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
4481           (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
4482            TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4483          && "Lowering produced unexpected number of results!");
4484
4485   // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4486   if (Result != TmpRes.getNode() && Result->use_empty()) {
4487     HandleSDNode Dummy(DAG.getRoot());
4488     DAG.RemoveDeadNode(Result);
4489   }
4490
4491   Result = TmpRes.getNode();
4492   
4493   unsigned NumArgRegs = Result->getNumValues() - 1;
4494   DAG.setRoot(SDValue(Result, NumArgRegs));
4495
4496   // Set up the return result vector.
4497   unsigned i = 0;
4498   unsigned Idx = 1;
4499   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 
4500       ++I, ++Idx) {
4501     SmallVector<MVT, 4> ValueVTs;
4502     ComputeValueVTs(*this, I->getType(), ValueVTs);
4503     for (unsigned Value = 0, NumValues = ValueVTs.size();
4504          Value != NumValues; ++Value) {
4505       MVT VT = ValueVTs[Value];
4506       MVT PartVT = getRegisterType(VT);
4507
4508       unsigned NumParts = getNumRegisters(VT);
4509       SmallVector<SDValue, 4> Parts(NumParts);
4510       for (unsigned j = 0; j != NumParts; ++j)
4511         Parts[j] = SDValue(Result, i++);
4512
4513       ISD::NodeType AssertOp = ISD::DELETED_NODE;
4514       if (F.paramHasAttr(Idx, ParamAttr::SExt))
4515         AssertOp = ISD::AssertSext;
4516       else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4517         AssertOp = ISD::AssertZext;
4518
4519       ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4520                                            AssertOp));
4521     }
4522   }
4523   assert(i == NumArgRegs && "Argument register count mismatch!");
4524 }
4525
4526
4527 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4528 /// implementation, which just inserts an ISD::CALL node, which is later custom
4529 /// lowered by the target to something concrete.  FIXME: When all targets are
4530 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4531 std::pair<SDValue, SDValue>
4532 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
4533                             bool RetSExt, bool RetZExt, bool isVarArg,
4534                             unsigned CallingConv, bool isTailCall,
4535                             SDValue Callee,
4536                             ArgListTy &Args, SelectionDAG &DAG) {
4537   SmallVector<SDValue, 32> Ops;
4538   Ops.push_back(Chain);   // Op#0 - Chain
4539   Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4540   Ops.push_back(DAG.getConstant(isVarArg, getPointerTy()));    // Op#2 - VarArg
4541   Ops.push_back(DAG.getConstant(isTailCall, getPointerTy()));  // Op#3 - Tail
4542   Ops.push_back(Callee);
4543   
4544   // Handle all of the outgoing arguments.
4545   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4546     SmallVector<MVT, 4> ValueVTs;
4547     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4548     for (unsigned Value = 0, NumValues = ValueVTs.size();
4549          Value != NumValues; ++Value) {
4550       MVT VT = ValueVTs[Value];
4551       const Type *ArgTy = VT.getTypeForMVT();
4552       SDValue Op = SDValue(Args[i].Node.getNode(), Args[i].Node.getResNo() + Value);
4553       ISD::ArgFlagsTy Flags;
4554       unsigned OriginalAlignment =
4555         getTargetData()->getABITypeAlignment(ArgTy);
4556
4557       if (Args[i].isZExt)
4558         Flags.setZExt();
4559       if (Args[i].isSExt)
4560         Flags.setSExt();
4561       if (Args[i].isInReg)
4562         Flags.setInReg();
4563       if (Args[i].isSRet)
4564         Flags.setSRet();
4565       if (Args[i].isByVal) {
4566         Flags.setByVal();
4567         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4568         const Type *ElementTy = Ty->getElementType();
4569         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4570         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
4571         // For ByVal, alignment should come from FE.  BE will guess if this
4572         // info is not there but there are cases it cannot get right.
4573         if (Args[i].Alignment)
4574           FrameAlign = Args[i].Alignment;
4575         Flags.setByValAlign(FrameAlign);
4576         Flags.setByValSize(FrameSize);
4577       }
4578       if (Args[i].isNest)
4579         Flags.setNest();
4580       Flags.setOrigAlign(OriginalAlignment);
4581
4582       MVT PartVT = getRegisterType(VT);
4583       unsigned NumParts = getNumRegisters(VT);
4584       SmallVector<SDValue, 4> Parts(NumParts);
4585       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4586
4587       if (Args[i].isSExt)
4588         ExtendKind = ISD::SIGN_EXTEND;
4589       else if (Args[i].isZExt)
4590         ExtendKind = ISD::ZERO_EXTEND;
4591
4592       getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4593
4594       for (unsigned i = 0; i != NumParts; ++i) {
4595         // if it isn't first piece, alignment must be 1
4596         ISD::ArgFlagsTy MyFlags = Flags;
4597         if (NumParts > 1 && i == 0)
4598           MyFlags.setSplit();
4599         else if (i != 0)
4600           MyFlags.setOrigAlign(1);
4601
4602         Ops.push_back(Parts[i]);
4603         Ops.push_back(DAG.getArgFlags(MyFlags));
4604       }
4605     }
4606   }
4607   
4608   // Figure out the result value types. We start by making a list of
4609   // the potentially illegal return value types.
4610   SmallVector<MVT, 4> LoweredRetTys;
4611   SmallVector<MVT, 4> RetTys;
4612   ComputeValueVTs(*this, RetTy, RetTys);
4613
4614   // Then we translate that to a list of legal types.
4615   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4616     MVT VT = RetTys[I];
4617     MVT RegisterVT = getRegisterType(VT);
4618     unsigned NumRegs = getNumRegisters(VT);
4619     for (unsigned i = 0; i != NumRegs; ++i)
4620       LoweredRetTys.push_back(RegisterVT);
4621   }
4622   
4623   LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
4624   
4625   // Create the CALL node.
4626   SDValue Res = DAG.getNode(ISD::CALL,
4627                               DAG.getVTList(&LoweredRetTys[0],
4628                                             LoweredRetTys.size()),
4629                               &Ops[0], Ops.size());
4630   Chain = Res.getValue(LoweredRetTys.size() - 1);
4631
4632   // Gather up the call result into a single value.
4633   if (RetTy != Type::VoidTy) {
4634     ISD::NodeType AssertOp = ISD::DELETED_NODE;
4635
4636     if (RetSExt)
4637       AssertOp = ISD::AssertSext;
4638     else if (RetZExt)
4639       AssertOp = ISD::AssertZext;
4640
4641     SmallVector<SDValue, 4> ReturnValues;
4642     unsigned RegNo = 0;
4643     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4644       MVT VT = RetTys[I];
4645       MVT RegisterVT = getRegisterType(VT);
4646       unsigned NumRegs = getNumRegisters(VT);
4647       unsigned RegNoEnd = NumRegs + RegNo;
4648       SmallVector<SDValue, 4> Results;
4649       for (; RegNo != RegNoEnd; ++RegNo)
4650         Results.push_back(Res.getValue(RegNo));
4651       SDValue ReturnValue =
4652         getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4653                          AssertOp);
4654       ReturnValues.push_back(ReturnValue);
4655     }
4656     Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4657                              &ReturnValues[0], ReturnValues.size());
4658   }
4659
4660   return std::make_pair(Res, Chain);
4661 }
4662
4663 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
4664   assert(0 && "LowerOperation not implemented for this target!");
4665   abort();
4666   return SDValue();
4667 }
4668
4669
4670 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4671   SDValue Op = getValue(V);
4672   assert((Op.getOpcode() != ISD::CopyFromReg ||
4673           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4674          "Copy from a reg to the same reg!");
4675   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4676
4677   RegsForValue RFV(TLI, Reg, V->getType());
4678   SDValue Chain = DAG.getEntryNode();
4679   RFV.getCopyToRegs(Op, DAG, Chain, 0);
4680   PendingExports.push_back(Chain);
4681 }
4682
4683 #include "llvm/CodeGen/SelectionDAGISel.h"
4684
4685 void SelectionDAGISel::
4686 LowerArguments(BasicBlock *LLVMBB) {
4687   // If this is the entry block, emit arguments.
4688   Function &F = *LLVMBB->getParent();
4689   SDValue OldRoot = SDL->DAG.getRoot();
4690   SmallVector<SDValue, 16> Args;
4691   TLI.LowerArguments(F, SDL->DAG, Args);
4692
4693   unsigned a = 0;
4694   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4695        AI != E; ++AI) {
4696     SmallVector<MVT, 4> ValueVTs;
4697     ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4698     unsigned NumValues = ValueVTs.size();
4699     if (!AI->use_empty()) {
4700       SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
4701       // If this argument is live outside of the entry block, insert a copy from
4702       // whereever we got it to the vreg that other BB's will reference it as.
4703       DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
4704       if (VMI != FuncInfo->ValueMap.end()) {
4705         SDL->CopyValueToVirtualRegister(AI, VMI->second);
4706       }
4707     }
4708     a += NumValues;
4709   }
4710
4711   // Finally, if the target has anything special to do, allow it to do so.
4712   // FIXME: this should insert code into the DAG!
4713   EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
4714 }
4715
4716 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
4717 /// ensure constants are generated when needed.  Remember the virtual registers
4718 /// that need to be added to the Machine PHI nodes as input.  We cannot just
4719 /// directly add them, because expansion might result in multiple MBB's for one
4720 /// BB.  As such, the start of the BB might correspond to a different MBB than
4721 /// the end.
4722 ///
4723 void
4724 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
4725   TerminatorInst *TI = LLVMBB->getTerminator();
4726
4727   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
4728
4729   // Check successor nodes' PHI nodes that expect a constant to be available
4730   // from this block.
4731   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4732     BasicBlock *SuccBB = TI->getSuccessor(succ);
4733     if (!isa<PHINode>(SuccBB->begin())) continue;
4734     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
4735     
4736     // If this terminator has multiple identical successors (common for
4737     // switches), only handle each succ once.
4738     if (!SuccsHandled.insert(SuccMBB)) continue;
4739     
4740     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4741     PHINode *PN;
4742
4743     // At this point we know that there is a 1-1 correspondence between LLVM PHI
4744     // nodes and Machine PHI nodes, but the incoming operands have not been
4745     // emitted yet.
4746     for (BasicBlock::iterator I = SuccBB->begin();
4747          (PN = dyn_cast<PHINode>(I)); ++I) {
4748       // Ignore dead phi's.
4749       if (PN->use_empty()) continue;
4750
4751       unsigned Reg;
4752       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4753
4754       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4755         unsigned &RegOut = SDL->ConstantsOut[C];
4756         if (RegOut == 0) {
4757           RegOut = FuncInfo->CreateRegForValue(C);
4758           SDL->CopyValueToVirtualRegister(C, RegOut);
4759         }
4760         Reg = RegOut;
4761       } else {
4762         Reg = FuncInfo->ValueMap[PHIOp];
4763         if (Reg == 0) {
4764           assert(isa<AllocaInst>(PHIOp) &&
4765                  FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4766                  "Didn't codegen value into a register!??");
4767           Reg = FuncInfo->CreateRegForValue(PHIOp);
4768           SDL->CopyValueToVirtualRegister(PHIOp, Reg);
4769         }
4770       }
4771
4772       // Remember that this register needs to added to the machine PHI node as
4773       // the input for this MBB.
4774       SmallVector<MVT, 4> ValueVTs;
4775       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
4776       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
4777         MVT VT = ValueVTs[vti];
4778         unsigned NumRegisters = TLI.getNumRegisters(VT);
4779         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4780           SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4781         Reg += NumRegisters;
4782       }
4783     }
4784   }
4785   SDL->ConstantsOut.clear();
4786 }
4787
4788 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
4789 /// supports legal types, and it emits MachineInstrs directly instead of
4790 /// creating SelectionDAG nodes.
4791 ///
4792 bool
4793 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
4794                                                       FastISel *F) {
4795   TerminatorInst *TI = LLVMBB->getTerminator();
4796
4797   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
4798   unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
4799
4800   // Check successor nodes' PHI nodes that expect a constant to be available
4801   // from this block.
4802   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4803     BasicBlock *SuccBB = TI->getSuccessor(succ);
4804     if (!isa<PHINode>(SuccBB->begin())) continue;
4805     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
4806     
4807     // If this terminator has multiple identical successors (common for
4808     // switches), only handle each succ once.
4809     if (!SuccsHandled.insert(SuccMBB)) continue;
4810     
4811     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4812     PHINode *PN;
4813
4814     // At this point we know that there is a 1-1 correspondence between LLVM PHI
4815     // nodes and Machine PHI nodes, but the incoming operands have not been
4816     // emitted yet.
4817     for (BasicBlock::iterator I = SuccBB->begin();
4818          (PN = dyn_cast<PHINode>(I)); ++I) {
4819       // Ignore dead phi's.
4820       if (PN->use_empty()) continue;
4821
4822       // Only handle legal types. Two interesting things to note here. First,
4823       // by bailing out early, we may leave behind some dead instructions,
4824       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
4825       // own moves. Second, this check is necessary becuase FastISel doesn't
4826       // use CreateRegForValue to create registers, so it always creates
4827       // exactly one register for each non-void instruction.
4828       MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
4829       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
4830         SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
4831         return false;
4832       }
4833
4834       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4835
4836       unsigned Reg = F->getRegForValue(PHIOp);
4837       if (Reg == 0) {
4838         SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
4839         return false;
4840       }
4841       SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
4842     }
4843   }
4844
4845   return true;
4846 }