diff --git a/lib/Analysis/DebugInfo.cpp b/lib/Analysis/DebugInfo.cpp index 5d275ddef28..a0721618964 100644 --- a/lib/Analysis/DebugInfo.cpp +++ b/lib/Analysis/DebugInfo.cpp @@ -793,7 +793,7 @@ DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) { /// CreateLocation - Creates a debug info location. DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo, - DIScope S, DILocation OrigLoc) { + DIScope S, DILocation OrigLoc) { Value *Elts[] = { ConstantInt::get(Type::getInt32Ty(VMContext), LineNo), ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo), @@ -1218,7 +1218,7 @@ namespace llvm { // If this location is already tracked then use it. DebugLocTuple Tuple(Context, Loc.getLineNumber(), - Loc.getColumnNumber()); + Loc.getColumnNumber()); DenseMap::iterator II = DebugLocInfo.DebugIdMap.find(Tuple); if (II != DebugLocInfo.DebugIdMap.end()) diff --git a/lib/AsmParser/LLParser.cpp b/lib/AsmParser/LLParser.cpp index 295329bf970..0ecf8473c1b 100644 --- a/lib/AsmParser/LLParser.cpp +++ b/lib/AsmParser/LLParser.cpp @@ -45,7 +45,7 @@ namespace llvm { t_InlineAsm, // Value in StrVal/StrVal2/UIntVal. t_Metadata // Value in MetadataVal. } Kind; - + LLParser::LocTy Loc; unsigned UIntVal; std::string StrVal, StrVal2; @@ -77,27 +77,27 @@ bool LLParser::ValidateEndOfModule() { return Error(ForwardRefTypeIDs.begin()->second.second, "use of undefined type '%" + utostr(ForwardRefTypeIDs.begin()->first) + "'"); - + if (!ForwardRefVals.empty()) return Error(ForwardRefVals.begin()->second.second, "use of undefined value '@" + ForwardRefVals.begin()->first + "'"); - + if (!ForwardRefValIDs.empty()) return Error(ForwardRefValIDs.begin()->second.second, "use of undefined value '@" + utostr(ForwardRefValIDs.begin()->first) + "'"); - + if (!ForwardRefMDNodes.empty()) return Error(ForwardRefMDNodes.begin()->second.second, "use of undefined metadata '!" + utostr(ForwardRefMDNodes.begin()->first) + "'"); - + // Look for intrinsic functions and CallInst that need to be upgraded for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove - + // Check debug info intrinsics. CheckDebugInfoIntrinsics(M); return false; @@ -160,7 +160,7 @@ bool LLParser::ParseTopLevelEntities() { return true; break; } - + case lltok::kw_thread_local: // OptionalThreadLocal case lltok::kw_addrspace: // OptionalAddrSpace case lltok::kw_constant: // GlobalType @@ -177,11 +177,11 @@ bool LLParser::ParseTopLevelEntities() { bool LLParser::ParseModuleAsm() { assert(Lex.getKind() == lltok::kw_module); Lex.Lex(); - - std::string AsmStr; + + std::string AsmStr; if (ParseToken(lltok::kw_asm, "expected 'module asm'") || ParseStringConstant(AsmStr)) return true; - + const std::string &AsmSoFar = M->getModuleInlineAsm(); if (AsmSoFar.empty()) M->setModuleInlineAsm(AsmStr); @@ -227,7 +227,7 @@ bool LLParser::ParseDepLibs() { if (EatIfPresent(lltok::rsquare)) return false; - + std::string Str; if (ParseStringConstant(Str)) return true; M->addLibrary(Str); @@ -263,21 +263,21 @@ bool LLParser::ParseUnnamedType() { PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseType(Ty)) return true; - + // See if this type was previously referenced. std::map >::iterator FI = ForwardRefTypeIDs.find(TypeID); if (FI != ForwardRefTypeIDs.end()) { if (FI->second.first.get() == Ty) return Error(TypeLoc, "self referential type is invalid"); - + cast(FI->second.first.get())->refineAbstractTypeTo(Ty); Ty = FI->second.first.get(); ForwardRefTypeIDs.erase(FI); } - + NumberedTypes.push_back(Ty); - + return false; } @@ -287,14 +287,14 @@ bool LLParser::ParseNamedType() { std::string Name = Lex.getStrVal(); LocTy NameLoc = Lex.getLoc(); Lex.Lex(); // eat LocalVar. - + PATypeHolder Ty(Type::getVoidTy(Context)); - + if (ParseToken(lltok::equal, "expected '=' after name") || ParseToken(lltok::kw_type, "expected 'type' after name") || ParseType(Ty)) return true; - + // Set the type name, checking for conflicts as we do so. bool AlreadyExists = M->addTypeName(Name, Ty); if (!AlreadyExists) return false; @@ -311,16 +311,16 @@ bool LLParser::ParseNamedType() { Ty = FI->second.first.get(); ForwardRefTypes.erase(FI); } - + // Inserting a name that is already defined, get the existing name. const Type *Existing = M->getTypeByName(Name); assert(Existing && "Conflict but no matching type?!"); - + // Otherwise, this is an attempt to redefine a type. That's okay if // the redefinition is identical to the original. // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0 if (Existing == Ty) return false; - + // Any other kind of (non-equivalent) redefinition is an error. return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" + Ty->getDescription() + "'"); @@ -332,7 +332,7 @@ bool LLParser::ParseNamedType() { bool LLParser::ParseDeclare() { assert(Lex.getKind() == lltok::kw_declare); Lex.Lex(); - + Function *F; return ParseFunctionHeader(F, false); } @@ -342,7 +342,7 @@ bool LLParser::ParseDeclare() { bool LLParser::ParseDefine() { assert(Lex.getKind() == lltok::kw_define); Lex.Lex(); - + Function *F; return ParseFunctionHeader(F, true) || ParseFunctionBody(*F); @@ -390,7 +390,7 @@ bool LLParser::ParseUnnamedGlobal() { if (ParseOptionalLinkage(Linkage, HasLinkage) || ParseOptionalVisibility(Visibility)) return true; - + if (HasLinkage || Lex.getKind() != lltok::kw_alias) return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); return ParseAlias(Name, NameLoc, Visibility); @@ -404,14 +404,14 @@ bool LLParser::ParseNamedGlobal() { LocTy NameLoc = Lex.getLoc(); std::string Name = Lex.getStrVal(); Lex.Lex(); - + bool HasLinkage; unsigned Linkage, Visibility; if (ParseToken(lltok::equal, "expected '=' in global variable") || ParseOptionalLinkage(Linkage, HasLinkage) || ParseOptionalVisibility(Visibility)) return true; - + if (HasLinkage || Lex.getKind() != lltok::kw_alias) return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility); return ParseAlias(Name, NameLoc, Visibility); @@ -432,7 +432,7 @@ bool LLParser::ParseMDNode(MetadataBase *&Node) { // !{ ..., !42, ... } unsigned MID = 0; if (ParseUInt32(MID)) return true; - + // Check existing MDNode. std::map::iterator I = MetadataCache.find(MID); if (I != MetadataCache.end()) { @@ -456,7 +456,7 @@ bool LLParser::ParseMDNode(MetadataBase *&Node) { ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); Node = FwdNode; return false; -} +} ///ParseNamedMetadata: /// !foo = !{ !1, !2 } @@ -493,7 +493,7 @@ bool LLParser::ParseNamedMetadata() { } /// ParseStandaloneMetadata: -/// !42 = !{...} +/// !42 = !{...} bool LLParser::ParseStandaloneMetadata() { assert(Lex.getKind() == lltok::Metadata); Lex.Lex(); @@ -509,7 +509,7 @@ bool LLParser::ParseStandaloneMetadata() { PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseType(Ty, TyLoc)) return true; - + if (Lex.getKind() != lltok::Metadata) return TokError("Expected metadata here"); @@ -518,7 +518,7 @@ bool LLParser::ParseStandaloneMetadata() { return TokError("Expected '{' here"); SmallVector Elts; - if (ParseMDNodeVector(Elts) + if (ParseMDNodeVector(Elts) || ParseToken(lltok::rbrace, "expected end of metadata node")) return true; @@ -560,7 +560,7 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, Linkage != GlobalValue::PrivateLinkage && Linkage != GlobalValue::LinkerPrivateLinkage) return Error(LinkageLoc, "invalid linkage type for alias"); - + Constant *Aliasee; LocTy AliaseeLoc = Lex.getLoc(); if (Lex.getKind() != lltok::kw_bitcast && @@ -574,7 +574,7 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, return Error(AliaseeLoc, "invalid aliasee"); Aliasee = ID.ConstantVal; } - + if (!isa(Aliasee->getType())) return Error(AliaseeLoc, "alias must have pointer type"); @@ -583,7 +583,7 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, (GlobalValue::LinkageTypes)Linkage, Name, Aliasee); GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); - + // See if this value already exists in the symbol table. If so, it is either // a redefinition or a definition of a forward reference. if (GlobalValue *Val = @@ -600,18 +600,18 @@ bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, if (Val->getType() != GA->getType()) return Error(NameLoc, "forward reference and definition of alias have different types"); - + // If they agree, just RAUW the old value with the alias and remove the // forward ref info. Val->replaceAllUsesWith(GA); Val->eraseFromParent(); ForwardRefVals.erase(I); } - + // Insert into the module, we know its name won't collide now. M->getAliasList().push_back(GA); assert(GA->getNameStr() == Name && "Should not be a name conflict!"); - + return false; } @@ -629,14 +629,14 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, unsigned AddrSpace; bool ThreadLocal, IsConstant; LocTy TyLoc; - + PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) || ParseOptionalAddrSpace(AddrSpace) || ParseGlobalType(IsConstant) || ParseType(Ty, TyLoc)) return true; - + // If the linkage is specified and is external, then no initializer is // present. Constant *Init = 0; @@ -649,7 +649,7 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, if (isa(Ty) || Ty == Type::getLabelTy(Context)) return Error(TyLoc, "invalid type for global variable"); - + GlobalVariable *GV = 0; // See if the global was forward referenced, if so, use the global. @@ -667,20 +667,20 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, } if (GV == 0) { - GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, + GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0, Name, 0, false, AddrSpace); } else { if (GV->getType()->getElementType() != Ty) return Error(TyLoc, "forward reference and definition of global have different types"); - + // Move the forward-reference to the correct spot in the module. M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); } if (Name.empty()) NumberedVals.push_back(GV); - + // Set the parsed properties on the global. if (Init) GV->setInitializer(Init); @@ -688,11 +688,11 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, GV->setLinkage((GlobalValue::LinkageTypes)Linkage); GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); GV->setThreadLocal(ThreadLocal); - + // Parse attributes on the global. while (Lex.getKind() == lltok::comma) { Lex.Lex(); - + if (Lex.getKind() == lltok::kw_section) { Lex.Lex(); GV->setSection(Lex.getStrVal()); @@ -706,7 +706,7 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, TokError("unknown global variable property!"); } } - + return false; } @@ -725,11 +725,11 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, Error(Loc, "global variable reference must have pointer type"); return 0; } - + // Look this name up in the normal function symbol table. GlobalValue *Val = cast_or_null(M->getValueSymbolTable().lookup(Name)); - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -738,7 +738,7 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, if (I != ForwardRefVals.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; @@ -746,7 +746,7 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, Val->getType()->getDescription() + "'"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. GlobalValue *FwdVal; if (const FunctionType *FT = dyn_cast(PTy->getElementType())) { @@ -755,13 +755,13 @@ GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty, Error(Loc, "function may not return opaque type"); return 0; } - + FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); } else { FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, GlobalValue::ExternalWeakLinkage, 0, Name); } - + ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -772,9 +772,9 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { Error(Loc, "global variable reference must have pointer type"); return 0; } - + GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -783,7 +783,7 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { if (I != ForwardRefValIDs.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; @@ -791,7 +791,7 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { Val->getType()->getDescription() + "'"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. GlobalValue *FwdVal; if (const FunctionType *FT = dyn_cast(PTy->getElementType())) { @@ -805,7 +805,7 @@ GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) { FwdVal = new GlobalVariable(*M, PTy->getElementType(), false, GlobalValue::ExternalWeakLinkage, 0, ""); } - + ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -858,7 +858,7 @@ bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { return ParseToken(lltok::lparen, "expected '(' in address space") || ParseUInt32(AddrSpace) || ParseToken(lltok::rparen, "expected ')' in address space"); -} +} /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind /// indicates what kind of attribute list this is: 0: function arg, 1: result, @@ -867,7 +867,7 @@ bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { Attrs = Attribute::None; LocTy AttrLoc = Lex.getLoc(); - + while (1) { switch (Lex.getKind()) { case lltok::kw_sext: @@ -888,10 +888,10 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { default: // End of attributes. if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly)) return Error(AttrLoc, "invalid use of function-only attribute"); - + if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly)) return Error(AttrLoc, "invalid use of parameter-only attribute"); - + return false; case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break; case lltok::kw_signext: Attrs |= Attribute::SExt; break; @@ -915,7 +915,7 @@ bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) { case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break; case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break; case lltok::kw_naked: Attrs |= Attribute::Naked; break; - + case lltok::kw_align: { unsigned Alignment; if (ParseOptionalAlignment(Alignment)) @@ -974,7 +974,7 @@ bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) { /// ::= 'default' /// ::= 'hidden' /// ::= 'protected' -/// +/// bool LLParser::ParseOptionalVisibility(unsigned &Res) { switch (Lex.getKind()) { default: Res = GlobalValue::DefaultVisibility; return false; @@ -1020,7 +1020,7 @@ bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) { } break; } - + Lex.Lex(); return false; } @@ -1037,13 +1037,13 @@ bool LLParser::ParseOptionalDbgInfo() { Lex.Lex(); MetadataBase *Node; if (ParseMDNode(Node)) return true; - + Metadata &TheMetadata = M->getContext().getMetadata(); unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); if (!MDDbgKind) MDDbgKind = TheMetadata.RegisterMDKind("dbg"); MDsOnInst.push_back(std::make_pair(MDDbgKind, cast(Node))); - + return false; } @@ -1074,7 +1074,7 @@ bool LLParser::ParseOptionalInfo(unsigned &Alignment) { } else return true; } while (EatIfPresent(lltok::comma)); - + return false; } @@ -1084,13 +1084,13 @@ bool LLParser::ParseOptionalInfo(unsigned &Alignment) { bool LLParser::ParseIndexList(SmallVectorImpl &Indices) { if (Lex.getKind() != lltok::comma) return TokError("expected ',' as start of index list"); - + while (EatIfPresent(lltok::comma)) { unsigned Idx; if (ParseUInt32(Idx)) return true; Indices.push_back(Idx); } - + return false; } @@ -1102,14 +1102,14 @@ bool LLParser::ParseIndexList(SmallVectorImpl &Indices) { bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) { LocTy TypeLoc = Lex.getLoc(); if (ParseTypeRec(Result)) return true; - + // Verify no unresolved uprefs. if (!UpRefs.empty()) return Error(UpRefs.back().Loc, "invalid unresolved type up reference"); - + if (!AllowVoid && Result.get() == Type::getVoidTy(Context)) return Error(TypeLoc, "void type only allowed for function results"); - + return false; } @@ -1124,26 +1124,26 @@ PATypeHolder LLParser::HandleUpRefs(const Type *ty) { // If Ty isn't abstract, or if there are no up-references in it, then there is // nothing to resolve here. if (!ty->isAbstract() || UpRefs.empty()) return ty; - + PATypeHolder Ty(ty); #if 0 errs() << "Type '" << Ty->getDescription() << "' newly formed. Resolving upreferences.\n" << UpRefs.size() << " upreferences active!\n"; #endif - + // If we find any resolvable upreferences (i.e., those whose NestingLevel goes // to zero), we resolve them all together before we resolve them to Ty. At // the end of the loop, if there is anything to resolve to Ty, it will be in // this variable. OpaqueType *TypeToResolve = 0; - + for (unsigned i = 0; i != UpRefs.size(); ++i) { // Determine if 'Ty' directly contains this up-references 'LastContainedTy'. bool ContainsType = std::find(Ty->subtype_begin(), Ty->subtype_end(), UpRefs[i].LastContainedTy) != Ty->subtype_end(); - + #if 0 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", " << UpRefs[i].LastContainedTy->getDescription() << ") = " @@ -1152,15 +1152,15 @@ PATypeHolder LLParser::HandleUpRefs(const Type *ty) { #endif if (!ContainsType) continue; - + // Decrement level of upreference unsigned Level = --UpRefs[i].NestingLevel; UpRefs[i].LastContainedTy = Ty; - + // If the Up-reference has a non-zero level, it shouldn't be resolved yet. if (Level != 0) continue; - + #if 0 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n"; #endif @@ -1171,10 +1171,10 @@ PATypeHolder LLParser::HandleUpRefs(const Type *ty) { UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list. --i; // Do not skip the next element. } - + if (TypeToResolve) TypeToResolve->refineAbstractTypeTo(Ty); - + return Ty; } @@ -1188,7 +1188,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { case lltok::Type: // TypeRec ::= 'float' | 'void' (etc) Result = Lex.getTyVal(); - Lex.Lex(); + Lex.Lex(); break; case lltok::kw_opaque: // TypeRec ::= 'opaque' @@ -1230,7 +1230,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { } Lex.Lex(); break; - + case lltok::LocalVarID: // TypeRec ::= %4 if (Lex.getUIntVal() < NumberedTypes.size()) @@ -1260,12 +1260,12 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { break; } } - - // Parse the type suffixes. + + // Parse the type suffixes. while (1) { switch (Lex.getKind()) { // End of type. - default: return false; + default: return false; // TypeRec ::= TypeRec '*' case lltok::star: @@ -1295,7 +1295,7 @@ bool LLParser::ParseTypeRec(PATypeHolder &Result) { Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace)); break; } - + /// Types '(' ArgTypeListI ')' OptFuncAttrs case lltok::lparen: if (ParseFunctionType(Result)) @@ -1314,13 +1314,13 @@ bool LLParser::ParseParameterList(SmallVectorImpl &ArgList, PerFunctionState &PFS) { if (ParseToken(lltok::lparen, "expected '(' in call")) return true; - + while (Lex.getKind() != lltok::rparen) { // If this isn't the first argument, we need a comma. if (!ArgList.empty() && ParseToken(lltok::comma, "expected ',' in argument list")) return true; - + // Parse the argument. LocTy ArgLoc; PATypeHolder ArgTy(Type::getVoidTy(Context)); @@ -1356,7 +1356,7 @@ bool LLParser::ParseArgumentList(std::vector &ArgList, isVarArg = false; assert(Lex.getKind() == lltok::lparen); Lex.Lex(); // eat the (. - + if (Lex.getKind() == lltok::rparen) { // empty } else if (Lex.getKind() == lltok::dotdotdot) { @@ -1367,16 +1367,16 @@ bool LLParser::ParseArgumentList(std::vector &ArgList, PATypeHolder ArgTy(Type::getVoidTy(Context)); unsigned Attrs; std::string Name; - + // If we're parsing a type, use ParseTypeRec, because we allow recursive // types (such as a function returning a pointer to itself). If parsing a // function prototype, we require fully resolved types. if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) || ParseOptionalAttrs(Attrs, 0)) return true; - + if (ArgTy == Type::getVoidTy(Context)) return Error(TypeLoc, "argument can not have void type"); - + if (Lex.getKind() == lltok::LocalVar || Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0 Name = Lex.getStrVal(); @@ -1385,16 +1385,16 @@ bool LLParser::ParseArgumentList(std::vector &ArgList, if (!FunctionType::isValidArgumentType(ArgTy)) return Error(TypeLoc, "invalid type for function argument"); - + ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); - + while (EatIfPresent(lltok::comma)) { // Handle ... at end of arg list. if (EatIfPresent(lltok::dotdotdot)) { isVarArg = true; break; } - + // Otherwise must be an argument type. TypeLoc = Lex.getLoc(); if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) || @@ -1413,14 +1413,14 @@ bool LLParser::ParseArgumentList(std::vector &ArgList, if (!ArgTy->isFirstClassType() && !isa(ArgTy)) return Error(TypeLoc, "invalid type for function argument"); - + ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name)); } } - + return ParseToken(lltok::rparen, "expected ')' at end of argument list"); } - + /// ParseFunctionType /// ::= Type ArgumentList OptionalAttrs bool LLParser::ParseFunctionType(PATypeHolder &Result) { @@ -1428,7 +1428,7 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { if (!FunctionType::isValidReturnType(Result)) return TokError("invalid function return type"); - + std::vector ArgList; bool isVarArg; unsigned Attrs; @@ -1437,7 +1437,7 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { // FIXME: Remove in LLVM 3.0 ParseOptionalAttrs(Attrs, 2)) return true; - + // Reject names on the arguments lists. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { if (!ArgList[i].Name.empty()) @@ -1448,11 +1448,11 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0 } } - + std::vector ArgListTy; for (unsigned i = 0, e = ArgList.size(); i != e; ++i) ArgListTy.push_back(ArgList[i].Type); - + Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg)); return false; @@ -1467,7 +1467,7 @@ bool LLParser::ParseFunctionType(PATypeHolder &Result) { bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) { assert(Lex.getKind() == lltok::lbrace); Lex.Lex(); // Consume the '{' - + if (EatIfPresent(lltok::rbrace)) { Result = StructType::get(Context, Packed); return false; @@ -1477,27 +1477,27 @@ bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) { LocTy EltTyLoc = Lex.getLoc(); if (ParseTypeRec(Result)) return true; ParamsList.push_back(Result); - + if (Result == Type::getVoidTy(Context)) return Error(EltTyLoc, "struct element can not have void type"); if (!StructType::isValidElementType(Result)) return Error(EltTyLoc, "invalid element type for struct"); - + while (EatIfPresent(lltok::comma)) { EltTyLoc = Lex.getLoc(); if (ParseTypeRec(Result)) return true; - + if (Result == Type::getVoidTy(Context)) return Error(EltTyLoc, "struct element can not have void type"); if (!StructType::isValidElementType(Result)) return Error(EltTyLoc, "invalid element type for struct"); - + ParamsList.push_back(Result); } - + if (ParseToken(lltok::rbrace, "expected '}' at end of struct")) return true; - + std::vector ParamsListTy; for (unsigned i = 0, e = ParamsList.size(); i != e; ++i) ParamsListTy.push_back(ParamsList[i].get()); @@ -1507,32 +1507,32 @@ bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) { /// ParseArrayVectorType - Parse an array or vector type, assuming the first /// token has already been consumed. -/// TypeRec +/// TypeRec /// ::= '[' APSINTVAL 'x' Types ']' /// ::= '<' APSINTVAL 'x' Types '>' bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) { if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || Lex.getAPSIntVal().getBitWidth() > 64) return TokError("expected number in address space"); - + LocTy SizeLoc = Lex.getLoc(); uint64_t Size = Lex.getAPSIntVal().getZExtValue(); Lex.Lex(); - + if (ParseToken(lltok::kw_x, "expected 'x' after element count")) return true; LocTy TypeLoc = Lex.getLoc(); PATypeHolder EltTy(Type::getVoidTy(Context)); if (ParseTypeRec(EltTy)) return true; - + if (EltTy == Type::getVoidTy(Context)) return Error(TypeLoc, "array and vector element type cannot be void"); if (ParseToken(isVector ? lltok::greater : lltok::rsquare, "expected end of sequential type")) return true; - + if (isVector) { if (Size == 0) return Error(SizeLoc, "zero element vector is illegal"); @@ -1573,7 +1573,7 @@ LLParser::PerFunctionState::~PerFunctionState() { delete I->second.first; I->second.first = 0; } - + for (std::map >::iterator I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I) if (!isa(I->second.first)) { @@ -1604,7 +1604,7 @@ Value *LLParser::PerFunctionState::GetVal(const std::string &Name, const Type *Ty, LocTy Loc) { // Look this name up in the normal function symbol table. Value *Val = F.getValueSymbolTable().lookup(Name); - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -1613,7 +1613,7 @@ Value *LLParser::PerFunctionState::GetVal(const std::string &Name, if (I != ForwardRefVals.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; @@ -1624,21 +1624,21 @@ Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Val->getType()->getDescription() + "'"); return 0; } - + // Don't make placeholders with invalid type. if (!Ty->isFirstClassType() && !isa(Ty) && Ty != Type::getLabelTy(F.getContext())) { P.Error(Loc, "invalid use of a non-first-class type"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. Value *FwdVal; - if (Ty == Type::getLabelTy(F.getContext())) + if (Ty == Type::getLabelTy(F.getContext())) FwdVal = BasicBlock::Create(F.getContext(), Name, &F); else FwdVal = new Argument(Ty, Name); - + ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -1647,7 +1647,7 @@ Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty, LocTy Loc) { // Look this name up in the normal function symbol table. Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0; - + // If this is a forward reference for the value, see if we already created a // forward ref record. if (Val == 0) { @@ -1656,7 +1656,7 @@ Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty, if (I != ForwardRefValIDs.end()) Val = I->second.first; } - + // If we have the value in the symbol table or fwd-ref table, return it. if (Val) { if (Val->getType() == Ty) return Val; @@ -1667,20 +1667,20 @@ Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty, Val->getType()->getDescription() + "'"); return 0; } - + if (!Ty->isFirstClassType() && !isa(Ty) && Ty != Type::getLabelTy(F.getContext())) { P.Error(Loc, "invalid use of a non-first-class type"); return 0; } - + // Otherwise, create a new forward reference for this value and remember it. Value *FwdVal; - if (Ty == Type::getLabelTy(F.getContext())) + if (Ty == Type::getLabelTy(F.getContext())) FwdVal = BasicBlock::Create(F.getContext(), "", &F); else FwdVal = new Argument(Ty); - + ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); return FwdVal; } @@ -1696,23 +1696,23 @@ bool LLParser::PerFunctionState::SetInstName(int NameID, return P.Error(NameLoc, "instructions returning void cannot have a name"); return false; } - + // If this was a numbered instruction, verify that the instruction is the // expected value and resolve any forward references. if (NameStr.empty()) { // If neither a name nor an ID was specified, just use the next ID. if (NameID == -1) NameID = NumberedVals.size(); - + if (unsigned(NameID) != NumberedVals.size()) return P.Error(NameLoc, "instruction expected to be numbered '%" + utostr(NumberedVals.size()) + "'"); - + std::map >::iterator FI = ForwardRefValIDs.find(NameID); if (FI != ForwardRefValIDs.end()) { if (FI->second.first->getType() != Inst->getType()) - return P.Error(NameLoc, "instruction forward referenced with type '" + + return P.Error(NameLoc, "instruction forward referenced with type '" + FI->second.first->getType()->getDescription() + "'"); FI->second.first->replaceAllUsesWith(Inst); delete FI->second.first; @@ -1728,18 +1728,18 @@ bool LLParser::PerFunctionState::SetInstName(int NameID, FI = ForwardRefVals.find(NameStr); if (FI != ForwardRefVals.end()) { if (FI->second.first->getType() != Inst->getType()) - return P.Error(NameLoc, "instruction forward referenced with type '" + + return P.Error(NameLoc, "instruction forward referenced with type '" + FI->second.first->getType()->getDescription() + "'"); FI->second.first->replaceAllUsesWith(Inst); delete FI->second.first; ForwardRefVals.erase(FI); } - + // Set the name on the instruction. Inst->setName(NameStr); - + if (Inst->getNameStr() != NameStr) - return P.Error(NameLoc, "multiple definition of local value named '" + + return P.Error(NameLoc, "multiple definition of local value named '" + NameStr + "'"); return false; } @@ -1768,11 +1768,11 @@ BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, else BB = GetBB(Name, Loc); if (BB == 0) return 0; // Already diagnosed error. - + // Move the block to the end of the function. Forward ref'd blocks are // inserted wherever they happen to be referenced. F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); - + // Remove the block from forward ref sets. if (Name.empty()) { ForwardRefValIDs.erase(NumberedVals.size()); @@ -1781,7 +1781,7 @@ BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, // BB forward references are already in the function symbol table. ForwardRefVals.erase(Name); } - + return BB; } @@ -1839,7 +1839,7 @@ bool LLParser::ParseValID(ValID &ID) { return false; } case lltok::APSInt: - ID.APSIntVal = Lex.getAPSIntVal(); + ID.APSIntVal = Lex.getAPSIntVal(); ID.Kind = ValID::t_APSInt; break; case lltok::APFloat: @@ -1857,7 +1857,7 @@ bool LLParser::ParseValID(ValID &ID) { case lltok::kw_null: ID.Kind = ValID::t_Null; break; case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; - + case lltok::lbrace: { // ValID ::= '{' ConstVector '}' Lex.Lex(); @@ -1865,7 +1865,7 @@ bool LLParser::ParseValID(ValID &ID) { if (ParseGlobalValueVector(Elts) || ParseToken(lltok::rbrace, "expected end of struct constant")) return true; - + ID.ConstantVal = ConstantStruct::get(Context, Elts.data(), Elts.size(), false); ID.Kind = ValID::t_Constant; @@ -1876,7 +1876,7 @@ bool LLParser::ParseValID(ValID &ID) { // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. Lex.Lex(); bool isPackedStruct = EatIfPresent(lltok::lbrace); - + SmallVector Elts; LocTy FirstEltLoc = Lex.getLoc(); if (ParseGlobalValueVector(Elts) || @@ -1884,14 +1884,14 @@ bool LLParser::ParseValID(ValID &ID) { ParseToken(lltok::rbrace, "expected end of packed struct")) || ParseToken(lltok::greater, "expected end of constant")) return true; - + if (isPackedStruct) { ID.ConstantVal = ConstantStruct::get(Context, Elts.data(), Elts.size(), true); ID.Kind = ValID::t_Constant; return false; } - + if (Elts.empty()) return Error(ID.Loc, "constant vector must not be empty"); @@ -1899,14 +1899,14 @@ bool LLParser::ParseValID(ValID &ID) { !Elts[0]->getType()->isFloatingPoint()) return Error(FirstEltLoc, "vector elements must have integer or floating point type"); - + // Verify that all the vector elements have the same type. for (unsigned i = 1, e = Elts.size(); i != e; ++i) if (Elts[i]->getType() != Elts[0]->getType()) return Error(FirstEltLoc, "vector element #" + utostr(i) + " is not of type '" + Elts[0]->getType()->getDescription()); - + ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size()); ID.Kind = ValID::t_Constant; return false; @@ -1926,13 +1926,13 @@ bool LLParser::ParseValID(ValID &ID) { ID.Kind = ValID::t_EmptyArray; return false; } - + if (!Elts[0]->getType()->isFirstClassType()) - return Error(FirstEltLoc, "invalid array element type: " + + return Error(FirstEltLoc, "invalid array element type: " + Elts[0]->getType()->getDescription()); - + ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); - + // Verify all elements are correct type! for (unsigned i = 0, e = Elts.size(); i != e; ++i) { if (Elts[i]->getType() != Elts[0]->getType()) @@ -1940,7 +1940,7 @@ bool LLParser::ParseValID(ValID &ID) { "array element #" + utostr(i) + " is not of type '" +Elts[0]->getType()->getDescription()); } - + ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size()); ID.Kind = ValID::t_Constant; return false; @@ -1966,7 +1966,7 @@ bool LLParser::ParseValID(ValID &ID) { ID.Kind = ValID::t_InlineAsm; return false; } - + case lltok::kw_trunc: case lltok::kw_zext: case lltok::kw_sext: @@ -1976,9 +1976,9 @@ bool LLParser::ParseValID(ValID &ID) { case lltok::kw_uitofp: case lltok::kw_sitofp: case lltok::kw_fptoui: - case lltok::kw_fptosi: + case lltok::kw_fptosi: case lltok::kw_inttoptr: - case lltok::kw_ptrtoint: { + case lltok::kw_ptrtoint: { unsigned Opc = Lex.getUIntVal(); PATypeHolder DestTy(Type::getVoidTy(Context)); Constant *SrcVal; @@ -1993,7 +1993,7 @@ bool LLParser::ParseValID(ValID &ID) { return Error(ID.Loc, "invalid cast opcode for cast from '" + SrcVal->getType()->getDescription() + "' to '" + DestTy->getDescription() + "'"); - ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, + ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal, DestTy); ID.Kind = ValID::t_Constant; return false; @@ -2050,12 +2050,12 @@ bool LLParser::ParseValID(ValID &ID) { ParseGlobalTypeAndValue(Val1) || ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) return true; - + if (Val0->getType() != Val1->getType()) return Error(ID.Loc, "compare operands must have the same type"); - + CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; - + if (Opc == Instruction::FCmp) { if (!Val0->getType()->isFPOrFPVector()) return Error(ID.Loc, "fcmp requires floating point operands"); @@ -2070,7 +2070,7 @@ bool LLParser::ParseValID(ValID &ID) { ID.Kind = ValID::t_Constant; return false; } - + // Binary Operators. case lltok::kw_add: case lltok::kw_fadd: @@ -2133,7 +2133,7 @@ bool LLParser::ParseValID(ValID &ID) { ID.Kind = ValID::t_Constant; return false; } - + // Logical Operations case lltok::kw_shl: case lltok::kw_lshr: @@ -2158,8 +2158,8 @@ bool LLParser::ParseValID(ValID &ID) { ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); ID.Kind = ValID::t_Constant; return false; - } - + } + case lltok::kw_getelementptr: case lltok::kw_shufflevector: case lltok::kw_insertelement: @@ -2175,11 +2175,11 @@ bool LLParser::ParseValID(ValID &ID) { ParseGlobalValueVector(Elts) || ParseToken(lltok::rparen, "expected ')' in constantexpr")) return true; - + if (Opc == Instruction::GetElementPtr) { if (Elts.size() == 0 || !isa(Elts[0]->getType())) return Error(ID.Loc, "getelementptr requires pointer operand"); - + if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), (Value**)(Elts.data() + 1), Elts.size() - 1)) @@ -2219,12 +2219,12 @@ bool LLParser::ParseValID(ValID &ID) { ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); } - + ID.Kind = ValID::t_Constant; return false; } } - + Lex.Lex(); return false; } @@ -2243,9 +2243,9 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, Constant *&V) { if (isa(Ty)) return Error(ID.Loc, "functions are not values, refer to them as pointers"); - + switch (ID.Kind) { - default: llvm_unreachable("Unknown ValID!"); + default: llvm_unreachable("Unknown ValID!"); case ValID::t_Metadata: return Error(ID.Loc, "invalid use of metadata"); case ValID::t_LocalID: @@ -2269,7 +2269,7 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, if (!Ty->isFloatingPoint() || !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) return Error(ID.Loc, "floating point constant invalid for type"); - + // The lexer has no type info, so builds all float and double FP constants // as double. Fix this here. Long double does not need this. if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble && @@ -2279,11 +2279,11 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, &Ignored); } V = ConstantFP::get(Context, ID.APFloatVal); - + if (V->getType() != Ty) return Error(ID.Loc, "floating point constant does not have type '" + Ty->getDescription() + "'"); - + return false; case ValID::t_Null: if (!isa(Ty)) @@ -2315,12 +2315,12 @@ bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, return false; } } - + bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { PATypeHolder Type(Type::getVoidTy(Context)); return ParseType(Type) || ParseGlobalValue(Type, V); -} +} /// ParseGlobalValueVector /// ::= /*empty*/ @@ -2332,16 +2332,16 @@ bool LLParser::ParseGlobalValueVector(SmallVectorImpl &Elts) { Lex.getKind() == lltok::greater || Lex.getKind() == lltok::rparen) return false; - + Constant *C; if (ParseGlobalTypeAndValue(C)) return true; Elts.push_back(C); - + while (EatIfPresent(lltok::comma)) { if (ParseGlobalTypeAndValue(C)) return true; Elts.push_back(C); } - + return false; } @@ -2397,7 +2397,7 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { // Parse the linkage. LocTy LinkageLoc = Lex.getLoc(); unsigned Linkage; - + unsigned Visibility, RetAttrs; CallingConv::ID CC; PATypeHolder RetType(Type::getVoidTy(Context)); @@ -2435,11 +2435,11 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { case GlobalValue::CommonLinkage: return Error(LinkageLoc, "invalid function linkage type"); } - + if (!FunctionType::isValidReturnType(RetType) || isa(RetType)) return Error(RetTypeLoc, "invalid function return type"); - + LocTy NameLoc = Lex.getLoc(); std::string FunctionName; @@ -2454,12 +2454,12 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { } else { return TokError("expected function name"); } - + Lex.Lex(); - + if (Lex.getKind() != lltok::lparen) return TokError("expected '(' in function argument list"); - + std::vector ArgList; bool isVarArg; unsigned FuncAttrs; @@ -2481,22 +2481,22 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs); FuncAttrs &= ~Attribute::Alignment; } - + // Okay, if we got here, the function is syntactically valid. Convert types // and do semantic checks. std::vector ParamTypeList; SmallVector Attrs; - // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function + // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function // attributes. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; if (FuncAttrs & ObsoleteFuncAttrs) { RetAttrs |= FuncAttrs & ObsoleteFuncAttrs; FuncAttrs &= ~ObsoleteFuncAttrs; } - + if (RetAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); - + for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { ParamTypeList.push_back(ArgList[i].Type); if (ArgList[i].Attrs != Attribute::None) @@ -2507,11 +2507,11 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs)); AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); - + if (PAL.paramHasAttr(1, Attribute::StructRet) && RetType != Type::getVoidTy(Context)) - return Error(RetTypeLoc, "functions with 'sret' argument must return void"); - + return Error(RetTypeLoc, "functions with 'sret' argument must return void"); + const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg); const PointerType *PFT = PointerType::getUnqual(FT); @@ -2542,7 +2542,7 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { AI->setName(""); } } - + } else { // If this is a definition of a forward referenced function, make sure the // types agree. @@ -2564,7 +2564,7 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { if (FunctionName.empty()) NumberedVals.push_back(Fn); - + Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); Fn->setCallingConv(CC); @@ -2572,21 +2572,21 @@ bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { Fn->setAlignment(Alignment); Fn->setSection(Section); if (!GC.empty()) Fn->setGC(GC.c_str()); - + // Add all of the arguments we parsed to the function. Function::arg_iterator ArgIt = Fn->arg_begin(); for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { // If the argument has a name, insert it into the argument symbol table. if (ArgList[i].Name.empty()) continue; - + // Set the name, if it conflicted, it will be auto-renamed. ArgIt->setName(ArgList[i].Name); - + if (ArgIt->getNameStr() != ArgList[i].Name) return Error(ArgList[i].Loc, "redefinition of argument '%" + ArgList[i].Name + "'"); } - + return false; } @@ -2599,15 +2599,15 @@ bool LLParser::ParseFunctionBody(Function &Fn) { if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin) return TokError("expected '{' in function body"); Lex.Lex(); // eat the {. - + PerFunctionState PFS(*this, Fn); - + while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end) if (ParseBasicBlock(PFS)) return true; - + // Eat the }. Lex.Lex(); - + // Verify function is ok. return PFS.VerifyFunctionComplete(); } @@ -2622,12 +2622,12 @@ bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { Name = Lex.getStrVal(); Lex.Lex(); } - + BasicBlock *BB = PFS.DefineBB(Name, NameLoc); if (BB == 0) return true; - + std::string NameStr; - + // Parse the instructions in this block until we get a terminator. Instruction *Inst; do { @@ -2636,7 +2636,7 @@ bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { LocTy NameLoc = Lex.getLoc(); int NameID = -1; NameStr = ""; - + if (Lex.getKind() == lltok::LocalVarID) { NameID = Lex.getUIntVal(); Lex.Lex(); @@ -2657,8 +2657,8 @@ bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { // Set metadata attached with this instruction. Metadata &TheMetadata = M->getContext().getMetadata(); - for (SmallVector, 2>::iterator - MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI) + for (SmallVector, 2>::iterator + MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI) TheMetadata.setMD(MDI->first, MDI->second, Inst); MDsOnInst.clear(); @@ -2667,7 +2667,7 @@ bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { // Set the name on the instruction. if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; } while (!isa(Inst)); - + return false; } @@ -2685,7 +2685,7 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, LocTy Loc = Lex.getLoc(); unsigned KeywordVal = Lex.getUIntVal(); Lex.Lex(); // Eat the keyword. - + switch (Token) { default: return Error(Loc, "expected instruction opcode"); // Terminator Instructions. @@ -2763,7 +2763,7 @@ bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, case lltok::kw_uitofp: case lltok::kw_sitofp: case lltok::kw_fptoui: - case lltok::kw_fptosi: + case lltok::kw_fptosi: case lltok::kw_inttoptr: case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); // Other. @@ -2843,20 +2843,20 @@ bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { /// ParseRet - Parse a return instruction. /// ::= 'ret' void (',' 'dbg' !1) /// ::= 'ret' TypeAndValue (',' 'dbg' !1) -/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' 'dbg' !1) +/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' 'dbg' !1) /// [[obsolete: LLVM 3.0]] bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS) { PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseType(Ty, true /*void allowed*/)) return true; - + if (Ty == Type::getVoidTy(Context)) { if (EatIfPresent(lltok::comma)) if (ParseOptionalDbgInfo()) return true; Inst = ReturnInst::Create(Context); return false; } - + Value *RV; if (ParseValue(Ty, RV, PFS)) return true; @@ -2870,20 +2870,20 @@ bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, // of 'ret {i32,i32} {i32 1, i32 2}' SmallVector RVs; RVs.push_back(RV); - + do { - // If optional 'dbg' is seen then this is the end of MRV. - if (Lex.getKind() == lltok::kw_dbg) - break; - if (ParseTypeAndValue(RV, PFS)) return true; - RVs.push_back(RV); + // If optional 'dbg' is seen then this is the end of MRV. + if (Lex.getKind() == lltok::kw_dbg) + break; + if (ParseTypeAndValue(RV, PFS)) return true; + RVs.push_back(RV); } while (EatIfPresent(lltok::comma)); RV = UndefValue::get(PFS.getFunction().getReturnType()); for (unsigned i = 0, e = RVs.size(); i != e; ++i) { - Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv"); - BB->getInstList().push_back(I); - RV = I; + Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv"); + BB->getInstList().push_back(I); + RV = I; } } } @@ -2902,26 +2902,26 @@ bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { LocTy Loc, Loc2; Value *Op0, *Op1, *Op2; if (ParseTypeAndValue(Op0, Loc, PFS)) return true; - + if (BasicBlock *BB = dyn_cast(Op0)) { Inst = BranchInst::Create(BB); return false; } - + if (Op0->getType() != Type::getInt1Ty(Context)) return Error(Loc, "branch condition must have 'i1' type"); - + if (ParseToken(lltok::comma, "expected ',' after branch condition") || ParseTypeAndValue(Op1, Loc, PFS) || ParseToken(lltok::comma, "expected ',' after true destination") || ParseTypeAndValue(Op2, Loc2, PFS)) return true; - + if (!isa(Op1)) return Error(Loc, "true destination of branch must be a basic block"); if (!isa(Op2)) return Error(Loc2, "true destination of branch must be a basic block"); - + Inst = BranchInst::Create(cast(Op1), cast(Op2), Op0); return false; } @@ -2944,13 +2944,13 @@ bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { return Error(CondLoc, "switch condition must have integer type"); if (!isa(DefaultBB)) return Error(BBLoc, "default destination must be a basic block"); - + // Parse the jump table pairs. SmallPtrSet SeenCases; SmallVector, 32> Table; while (Lex.getKind() != lltok::rsquare) { Value *Constant, *DestBB; - + if (ParseTypeAndValue(Constant, CondLoc, PFS) || ParseToken(lltok::comma, "expected ',' after case value") || ParseTypeAndValue(DestBB, BBLoc, PFS)) @@ -2962,13 +2962,13 @@ bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { return Error(CondLoc, "case value is not a constant integer"); if (!isa(DestBB)) return Error(BBLoc, "case destination is not a basic block"); - + Table.push_back(std::make_pair(cast(Constant), cast(DestBB))); } - + Lex.Lex(); // Eat the ']'. - + SwitchInst *SI = SwitchInst::Create(Cond, cast(DefaultBB), Table.size()); for (unsigned i = 0, e = Table.size(); i != e; ++i) @@ -3001,12 +3001,12 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || ParseTypeAndValue(UnwindBB, PFS)) return true; - + if (!isa(NormalBB)) return Error(CallLoc, "normal destination is not a basic block"); if (!isa(UnwindBB)) return Error(CallLoc, "unwind destination is not a basic block"); - + // If RetType is a non-function pointer type, then this is the short syntax // for the call, which means that RetType is just the return type. Infer the // rest of the function argument types from the arguments that are present. @@ -3018,18 +3018,18 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { std::vector ParamTypes; for (unsigned i = 0, e = ArgList.size(); i != e; ++i) ParamTypes.push_back(ArgList[i].V->getType()); - + if (!FunctionType::isValidReturnType(RetType)) return Error(RetTypeLoc, "Invalid result type for LLVM function"); - + Ty = FunctionType::get(RetType, ParamTypes, false); PFTy = PointerType::getUnqual(Ty); } - + // Look up the callee. Value *Callee; if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; - + // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional // function attributes. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; @@ -3037,14 +3037,14 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { RetAttrs |= FnAttrs & ObsoleteFuncAttrs; FnAttrs &= ~ObsoleteFuncAttrs; } - + // Set up the Attributes for the function. SmallVector Attrs; if (RetAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); - + SmallVector Args; - + // Loop through FunctionType's arguments and ensure they are specified // correctly. Also, gather any parameter attributes. FunctionType::param_iterator I = Ty->param_begin(); @@ -3056,7 +3056,7 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { } else if (!Ty->isVarArg()) { return Error(ArgList[i].Loc, "too many arguments specified"); } - + if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) return Error(ArgList[i].Loc, "argument is not of expected type '" + ExpectedTy->getDescription() + "'"); @@ -3064,16 +3064,16 @@ bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { if (ArgList[i].Attrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); } - + if (I != E) return Error(CallLoc, "not enough parameters specified for call"); - + if (FnAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs)); - + // Finish off the Attributes and check them AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); - + InvokeInst *II = InvokeInst::Create(Callee, cast(NormalBB), cast(UnwindBB), Args.begin(), Args.end()); @@ -3112,10 +3112,10 @@ bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, case 1: Valid = LHS->getType()->isIntOrIntVector(); break; case 2: Valid = LHS->getType()->isFPOrFPVector(); break; } - + if (!Valid) return Error(Loc, "invalid operand type for instruction"); - + Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); return false; } @@ -3152,7 +3152,7 @@ bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, ParseToken(lltok::comma, "expected ',' after compare value") || ParseValue(LHS->getType(), RHS, PFS)) return true; - + if (Opc == Instruction::FCmp) { if (!LHS->getType()->isFPOrFPVector()) return Error(Loc, "fcmp requires floating point operands"); @@ -3182,7 +3182,7 @@ bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, ParseToken(lltok::kw_to, "expected 'to' after cast value") || ParseType(DestTy)) return true; - + if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); return Error(Loc, "invalid cast opcode for cast from '" + @@ -3204,10 +3204,10 @@ bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after select value") || ParseTypeAndValue(Op2, PFS)) return true; - + if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) return Error(Loc, Reason); - + Inst = SelectInst::Create(Op0, Op1, Op2); return false; } @@ -3222,7 +3222,7 @@ bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after vaarg operand") || ParseType(EltTy, TypeLoc)) return true; - + if (!EltTy->isFirstClassType()) return Error(TypeLoc, "va_arg requires operand with first class type"); @@ -3239,10 +3239,10 @@ bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after extract value") || ParseTypeAndValue(Op1, PFS)) return true; - + if (!ExtractElementInst::isValidOperands(Op0, Op1)) return Error(Loc, "invalid extractelement operands"); - + Inst = ExtractElementInst::Create(Op0, Op1); return false; } @@ -3258,10 +3258,10 @@ bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after insertelement value") || ParseTypeAndValue(Op2, PFS)) return true; - + if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) return Error(Loc, "invalid insertelement operands"); - + Inst = InsertElementInst::Create(Op0, Op1, Op2); return false; } @@ -3277,10 +3277,10 @@ bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after shuffle value") || ParseTypeAndValue(Op2, PFS)) return true; - + if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) return Error(Loc, "invalid extractelement operands"); - + Inst = new ShuffleVectorInst(Op0, Op1, Op2); return false; } @@ -3291,7 +3291,7 @@ bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { PATypeHolder Ty(Type::getVoidTy(Context)); Value *Op0, *Op1; LocTy TypeLoc = Lex.getLoc(); - + if (ParseType(Ty) || ParseToken(lltok::lsquare, "expected '[' in phi value list") || ParseValue(Ty, Op0, PFS) || @@ -3299,11 +3299,11 @@ bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { ParseValue(Type::getLabelTy(Context), Op1, PFS) || ParseToken(lltok::rsquare, "expected ']' in phi value list")) return true; - + SmallVector, 16> PHIVals; while (1) { PHIVals.push_back(std::make_pair(Op0, cast(Op1))); - + if (!EatIfPresent(lltok::comma)) break; @@ -3314,7 +3314,7 @@ bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::rsquare, "expected ']' in phi value list")) return true; } - + if (!Ty->isFirstClassType()) return Error(TypeLoc, "phi node must have first class type"); @@ -3338,7 +3338,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, ValID CalleeID; SmallVector ArgList; LocTy CallLoc = Lex.getLoc(); - + if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) || ParseOptionalCallingConv(CC) || ParseOptionalAttrs(RetAttrs, 1) || @@ -3347,7 +3347,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, ParseParameterList(ArgList, PFS) || ParseOptionalAttrs(FnAttrs, 2)) return true; - + // If RetType is a non-function pointer type, then this is the short syntax // for the call, which means that RetType is just the return type. Infer the // rest of the function argument types from the arguments that are present. @@ -3359,18 +3359,18 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, std::vector ParamTypes; for (unsigned i = 0, e = ArgList.size(); i != e; ++i) ParamTypes.push_back(ArgList[i].V->getType()); - + if (!FunctionType::isValidReturnType(RetType)) return Error(RetTypeLoc, "Invalid result type for LLVM function"); - + Ty = FunctionType::get(RetType, ParamTypes, false); PFTy = PointerType::getUnqual(Ty); } - + // Look up the callee. Value *Callee; if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true; - + // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional // function attributes. unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg; @@ -3383,9 +3383,9 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, SmallVector Attrs; if (RetAttrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(0, RetAttrs)); - + SmallVector Args; - + // Loop through FunctionType's arguments and ensure they are specified // correctly. Also, gather any parameter attributes. FunctionType::param_iterator I = Ty->param_begin(); @@ -3397,7 +3397,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, } else if (!Ty->isVarArg()) { return Error(ArgList[i].Loc, "too many arguments specified"); } - + if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) return Error(ArgList[i].Loc, "argument is not of expected type '" + ExpectedTy->getDescription() + "'"); @@ -3405,7 +3405,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, if (ArgList[i].Attrs != Attribute::None) Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs)); } - + if (I != E) return Error(CallLoc, "not enough parameters specified for call"); @@ -3414,7 +3414,7 @@ bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, // Finish off the Attributes and check them AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); - + CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end()); CI->setTailCall(isTail); CI->setCallingConv(CC); @@ -3444,7 +3444,7 @@ bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS, } else { if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true; if (EatIfPresent(lltok::comma)) - if (ParseOptionalInfo(Alignment)) return true; + if (ParseOptionalInfo(Alignment)) return true; } } @@ -3476,14 +3476,14 @@ bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS, Value *Val; LocTy Loc; unsigned Alignment = 0; if (ParseTypeAndValue(Val, Loc, PFS)) return true; - + if (EatIfPresent(lltok::comma)) if (ParseOptionalInfo(Alignment)) return true; if (!isa(Val->getType()) || !cast(Val->getType())->getElementType()->isFirstClassType()) return Error(Loc, "load operand must be a pointer to a first class type"); - + Inst = new LoadInst(Val, "", isVolatile, Alignment); return false; } @@ -3501,14 +3501,14 @@ bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS, if (EatIfPresent(lltok::comma)) if (ParseOptionalInfo(Alignment)) return true; - + if (!isa(Ptr->getType())) return Error(PtrLoc, "store operand must be a pointer"); if (!Val->getType()->isFirstClassType()) return Error(Loc, "store operand must be a first class value"); if (cast(Ptr->getType())->getElementType() != Val->getType()) return Error(Loc, "stored value and pointer type do not match"); - + Inst = new StoreInst(Val, Ptr, isVolatile, Alignment); return false; } @@ -3523,7 +3523,7 @@ bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) { ParseToken(lltok::comma, "expected ',' after getresult operand") || ParseUInt32(Element, EltLoc)) return true; - + if (!isa(Val->getType()) && !isa(Val->getType())) return Error(ValLoc, "getresult inst requires an aggregate operand"); if (!ExtractValueInst::getIndexedType(Val->getType(), Element)) @@ -3540,10 +3540,10 @@ bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { bool InBounds = EatIfPresent(lltok::kw_inbounds); if (ParseTypeAndValue(Ptr, Loc, PFS)) return true; - + if (!isa(Ptr->getType())) return Error(Loc, "base of getelementptr must be a pointer"); - + SmallVector Indices; while (EatIfPresent(lltok::comma)) { if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; @@ -3551,7 +3551,7 @@ bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { return Error(EltLoc, "getelementptr index must be an integer"); Indices.push_back(Val); } - + if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices.begin(), Indices.end())) return Error(Loc, "invalid getelementptr indices"); @@ -3590,10 +3590,10 @@ bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { ParseTypeAndValue(Val1, Loc1, PFS) || ParseIndexList(Indices)) return true; - + if (!isa(Val0->getType()) && !isa(Val0->getType())) return Error(Loc0, "extractvalue operand must be array or struct"); - + if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), Indices.end())) return Error(Loc0, "invalid indices for insertvalue"); diff --git a/lib/Bitcode/Reader/BitcodeReader.cpp b/lib/Bitcode/Reader/BitcodeReader.cpp index 70d2fc5907e..f3ab806271a 100644 --- a/lib/Bitcode/Reader/BitcodeReader.cpp +++ b/lib/Bitcode/Reader/BitcodeReader.cpp @@ -35,7 +35,7 @@ void BitcodeReader::FreeState() { std::vector().swap(TypeList); ValueList.clear(); MDValueList.clear(); - + std::vector().swap(MAttributes); std::vector().swap(FunctionBBs); std::vector().swap(FunctionsWithBodies); @@ -53,7 +53,7 @@ static bool ConvertToString(SmallVector &Record, unsigned Idx, StrTy &Result) { if (Idx > Record.size()) return true; - + for (unsigned i = Idx, e = Record.size(); i != e; ++i) Result += (char)Record[i]; return false; @@ -145,15 +145,15 @@ namespace { : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); } - + /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. static inline bool classof(const ConstantPlaceHolder *) { return true; } static bool classof(const Value *V) { - return isa(V) && + return isa(V) && cast(V)->getOpcode() == Instruction::UserOp1; } - - + + /// Provide fast operand accessors //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); }; @@ -171,16 +171,16 @@ void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { push_back(V); return; } - + if (Idx >= size()) resize(Idx+1); - + WeakVH &OldV = ValuePtrs[Idx]; if (OldV == 0) { OldV = V; return; } - + // Handle constants and non-constants (e.g. instrs) differently for // efficiency. if (Constant *PHC = dyn_cast(&*OldV)) { @@ -193,7 +193,7 @@ void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { delete PrevVal; } } - + Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, const Type *Ty) { @@ -214,15 +214,15 @@ Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) { if (Idx >= size()) resize(Idx + 1); - + if (Value *V = ValuePtrs[Idx]) { assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); return V; } - + // No type specified, must be invalid reference. if (Ty == 0) return 0; - + // Create and return a placeholder, which will later be RAUW'd. Value *V = new Argument(Ty); ValuePtrs[Idx] = V; @@ -237,30 +237,30 @@ Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) { /// uses and rewrite all the place holders at once for any constant that uses /// a placeholder. void BitcodeReaderValueList::ResolveConstantForwardRefs() { - // Sort the values by-pointer so that they are efficient to look up with a + // Sort the values by-pointer so that they are efficient to look up with a // binary search. std::sort(ResolveConstants.begin(), ResolveConstants.end()); - + SmallVector NewOps; - + while (!ResolveConstants.empty()) { Value *RealVal = operator[](ResolveConstants.back().second); Constant *Placeholder = ResolveConstants.back().first; ResolveConstants.pop_back(); - + // Loop over all users of the placeholder, updating them to reference the // new value. If they reference more than one placeholder, update them all // at once. while (!Placeholder->use_empty()) { Value::use_iterator UI = Placeholder->use_begin(); - + // If the using object isn't uniqued, just update the operands. This // handles instructions and initializers for global variables. if (!isa(*UI) || isa(*UI)) { UI.getUse().set(RealVal); continue; } - + // Otherwise, we have a constant that uses the placeholder. Replace that // constant with a new constant that has *all* placeholder uses updated. Constant *UserC = cast(*UI); @@ -275,8 +275,8 @@ void BitcodeReaderValueList::ResolveConstantForwardRefs() { NewOp = RealVal; } else { // Otherwise, look up the placeholder in ResolveConstants. - ResolveConstantsTy::iterator It = - std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), + ResolveConstantsTy::iterator It = + std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), std::pair(cast(*I), 0)); assert(It != ResolveConstants.end() && It->first == *I); @@ -301,12 +301,12 @@ void BitcodeReaderValueList::ResolveConstantForwardRefs() { NewC = cast(UserC)->getWithOperands(&NewOps[0], NewOps.size()); } - + UserC->replaceAllUsesWith(NewC); UserC->destroyConstant(); NewOps.clear(); } - + // Update all ValueHandles, they should be the only users at this point. Placeholder->replaceAllUsesWith(RealVal); delete Placeholder; @@ -318,16 +318,16 @@ void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { push_back(V); return; } - + if (Idx >= size()) resize(Idx+1); - + WeakVH &OldV = MDValuePtrs[Idx]; if (OldV == 0) { OldV = V; return; } - + // If there was a forward reference to this value, replace it. Value *PrevVal = OldV; OldV->replaceAllUsesWith(V); @@ -340,12 +340,12 @@ void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { if (Idx >= size()) resize(Idx + 1); - + if (Value *V = MDValuePtrs[Idx]) { assert(V->getType() == Type::getMetadataTy(Context) && "Type mismatch in value table!"); return V; } - + // Create and return a placeholder, which will later be RAUW'd. Value *V = new Argument(Type::getMetadataTy(Context)); MDValuePtrs[Idx] = V; @@ -357,7 +357,7 @@ const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) { if (ID < TypeList.size()) return TypeList[ID].get(); if (!isTypeTable) return 0; - + // The type table allows forward references. Push as many Opaque types as // needed to get up to ID. while (TypeList.size() <= ID) @@ -372,14 +372,14 @@ const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) { bool BitcodeReader::ParseAttributeBlock() { if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) return Error("Malformed block record"); - + if (!MAttributes.empty()) return Error("Multiple PARAMATTR blocks found!"); - + SmallVector Record; - + SmallVector Attrs; - + // Read all the records. while (1) { unsigned Code = Stream.ReadCode(); @@ -388,7 +388,7 @@ bool BitcodeReader::ParseAttributeBlock() { return Error("Error at end of PARAMATTR block"); return false; } - + if (Code == bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); @@ -396,12 +396,12 @@ bool BitcodeReader::ParseAttributeBlock() { return Error("Malformed block record"); continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. Record.clear(); switch (Stream.ReadRecord(Code, Record)) { @@ -440,14 +440,14 @@ bool BitcodeReader::ParseAttributeBlock() { unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn| Attribute::ReadOnly|Attribute::ReadNone); - + if (FnAttribute == Attribute::None && RetAttribute != Attribute::None && (RetAttribute & OldRetAttrs) != 0) { if (FnAttribute == Attribute::None) { // add a slot so they get added. Record.push_back(~0U); Record.push_back(0); } - + FnAttribute |= RetAttribute & OldRetAttrs; RetAttribute &= ~OldRetAttrs; } @@ -475,7 +475,7 @@ bool BitcodeReader::ParseAttributeBlock() { bool BitcodeReader::ParseTypeTable() { if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID)) return Error("Malformed block record"); - + if (!TypeList.empty()) return Error("Multiple TYPE_BLOCKs found!"); @@ -492,7 +492,7 @@ bool BitcodeReader::ParseTypeTable() { return Error("Error at end of type table block"); return false; } - + if (Code == bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); @@ -500,12 +500,12 @@ bool BitcodeReader::ParseTypeTable() { return Error("Malformed block record"); continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. Record.clear(); const Type *ResultTy = 0; @@ -550,10 +550,10 @@ bool BitcodeReader::ParseTypeTable() { case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] if (Record.size() < 1) return Error("Invalid Integer type record"); - + ResultTy = IntegerType::get(Context, Record[0]); break; - case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or + case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or // [pointee type, address space] if (Record.size() < 1) return Error("Invalid POINTER type record"); @@ -572,7 +572,7 @@ bool BitcodeReader::ParseTypeTable() { std::vector ArgTys; for (unsigned i = 3, e = Record.size(); i != e; ++i) ArgTys.push_back(getTypeByID(Record[i], true)); - + ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys, Record[0]); break; @@ -597,7 +597,7 @@ bool BitcodeReader::ParseTypeTable() { ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]); break; } - + if (NumRecords == TypeList.size()) { // If this is a new type slot, just append it. TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context)); @@ -612,14 +612,14 @@ bool BitcodeReader::ParseTypeTable() { // Resolve the opaque type to the real type now. assert(NumRecords < TypeList.size() && "Typelist imbalance"); const OpaqueType *OldTy = cast(TypeList[NumRecords++].get()); - + // Don't directly push the new type on the Tab. Instead we want to replace // the opaque type we previously inserted with the new concrete value. The // refinement from the abstract (opaque) type to the new type causes all // uses of the abstract type to use the concrete type (NewTy). This will // also cause the opaque type to be deleted. const_cast(OldTy)->refineAbstractTypeTo(ResultTy); - + // This should have replaced the old opaque type with the new type in the // value table... or with a preexisting type that was already in the // system. Let's just make sure it did. @@ -633,9 +633,9 @@ bool BitcodeReader::ParseTypeTable() { bool BitcodeReader::ParseTypeSymbolTable() { if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID)) return Error("Malformed block record"); - + SmallVector Record; - + // Read all the records for this type table. std::string TypeName; while (1) { @@ -645,7 +645,7 @@ bool BitcodeReader::ParseTypeSymbolTable() { return Error("Error at end of type symbol table block"); return false; } - + if (Code == bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); @@ -653,12 +653,12 @@ bool BitcodeReader::ParseTypeSymbolTable() { return Error("Malformed block record"); continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. Record.clear(); switch (Stream.ReadRecord(Code, Record)) { @@ -683,7 +683,7 @@ bool BitcodeReader::ParseValueSymbolTable() { return Error("Malformed block record"); SmallVector Record; - + // Read all the records for this value table. SmallString<128> ValueName; while (1) { @@ -692,7 +692,7 @@ bool BitcodeReader::ParseValueSymbolTable() { if (Stream.ReadBlockEnd()) return Error("Error at end of value symbol table block"); return false; - } + } if (Code == bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); @@ -700,12 +700,12 @@ bool BitcodeReader::ParseValueSymbolTable() { return Error("Malformed block record"); continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. Record.clear(); switch (Stream.ReadRecord(Code, Record)) { @@ -718,7 +718,7 @@ bool BitcodeReader::ParseValueSymbolTable() { if (ValueID >= ValueList.size()) return Error("Invalid Value ID in VST_ENTRY record"); Value *V = ValueList[ValueID]; - + V->setName(StringRef(ValueName.data(), ValueName.size())); ValueName.clear(); break; @@ -729,7 +729,7 @@ bool BitcodeReader::ParseValueSymbolTable() { BasicBlock *BB = getBasicBlock(Record[0]); if (BB == 0) return Error("Invalid BB ID in VST_BBENTRY record"); - + BB->setName(StringRef(ValueName.data(), ValueName.size())); ValueName.clear(); break; @@ -743,9 +743,9 @@ bool BitcodeReader::ParseMetadata() { if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) return Error("Malformed block record"); - + SmallVector Record; - + // Read all the records. while (1) { unsigned Code = Stream.ReadCode(); @@ -754,7 +754,7 @@ bool BitcodeReader::ParseMetadata() { return Error("Error at end of PARAMATTR block"); return false; } - + if (Code == bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); @@ -762,12 +762,12 @@ bool BitcodeReader::ParseMetadata() { return Error("Malformed block record"); continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. Record.clear(); switch (Stream.ReadRecord(Code, Record)) { @@ -795,7 +795,7 @@ bool BitcodeReader::ParseMetadata() { if (MetadataBase *B = dyn_cast(MD)) Elts.push_back(B); } - Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(), + Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(), Elts.size(), TheModule); MDValueList.AssignValue(V, NextValueNo++); break; @@ -803,7 +803,7 @@ bool BitcodeReader::ParseMetadata() { case bitc::METADATA_NODE: { if (Record.empty() || Record.size() % 2 == 1) return Error("Invalid METADATA_NODE record"); - + unsigned Size = Record.size(); SmallVector Elts; for (unsigned i = 0; i != Size; i += 2) { @@ -825,7 +825,7 @@ bool BitcodeReader::ParseMetadata() { String.resize(MDStringLength); for (unsigned i = 0; i != MDStringLength; ++i) String[i] = Record[i]; - Value *V = MDString::get(Context, + Value *V = MDString::get(Context, StringRef(String.data(), String.size())); MDValueList.AssignValue(V, NextValueNo++); break; @@ -833,16 +833,16 @@ bool BitcodeReader::ParseMetadata() { case bitc::METADATA_KIND: { unsigned RecordLength = Record.size(); if (Record.empty() || RecordLength < 2) - return Error("Invalid METADATA_KIND record"); + return Error("Invalid METADATA_KIND record"); SmallString<8> Name; Name.resize(RecordLength-1); MDKindID Kind = Record[0]; for (unsigned i = 1; i != RecordLength; ++i) - Name[i-1] = Record[i]; + Name[i-1] = Record[i]; Metadata &TheMetadata = Context.getMetadata(); - assert(TheMetadata.MDHandlerNames.find(Name.str()) - == TheMetadata.MDHandlerNames.end() && - "Already registered MDKind!"); + assert(TheMetadata.MDHandlerNames.find(Name.str()) + == TheMetadata.MDHandlerNames.end() && + "Already registered MDKind!"); TheMetadata.MDHandlerNames[Name.str()] = Kind; break; } @@ -855,7 +855,7 @@ bool BitcodeReader::ParseMetadata() { static uint64_t DecodeSignRotatedValue(uint64_t V) { if ((V & 1) == 0) return V >> 1; - if (V != 1) + if (V != 1) return -(V >> 1); // There is no such thing as -0 with integers. "-0" really means MININT. return 1ULL << 63; @@ -866,7 +866,7 @@ static uint64_t DecodeSignRotatedValue(uint64_t V) { bool BitcodeReader::ResolveGlobalAndAliasInits() { std::vector > GlobalInitWorklist; std::vector > AliasInitWorklist; - + GlobalInitWorklist.swap(GlobalInits); AliasInitWorklist.swap(AliasInits); @@ -881,7 +881,7 @@ bool BitcodeReader::ResolveGlobalAndAliasInits() { else return Error("Global variable initializer is not a constant!"); } - GlobalInitWorklist.pop_back(); + GlobalInitWorklist.pop_back(); } while (!AliasInitWorklist.empty()) { @@ -894,7 +894,7 @@ bool BitcodeReader::ResolveGlobalAndAliasInits() { else return Error("Alias initializer is not a constant!"); } - AliasInitWorklist.pop_back(); + AliasInitWorklist.pop_back(); } return false; } @@ -904,7 +904,7 @@ bool BitcodeReader::ParseConstants() { return Error("Malformed block record"); SmallVector Record; - + // Read all the records for this value table. const Type *CurTy = Type::getInt32Ty(Context); unsigned NextCstNo = ValueList.size(); @@ -912,7 +912,7 @@ bool BitcodeReader::ParseConstants() { unsigned Code = Stream.ReadCode(); if (Code == bitc::END_BLOCK) break; - + if (Code == bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); @@ -920,12 +920,12 @@ bool BitcodeReader::ParseConstants() { return Error("Malformed block record"); continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. Record.clear(); Value *V = 0; @@ -953,13 +953,13 @@ bool BitcodeReader::ParseConstants() { case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] if (!isa(CurTy) || Record.empty()) return Error("Invalid WIDE_INTEGER record"); - + unsigned NumWords = Record.size(); SmallVector Words; Words.resize(NumWords); for (unsigned i = 0; i != NumWords; ++i) Words[i] = DecodeSignRotatedValue(Record[i]); - V = ConstantInt::get(Context, + V = ConstantInt::get(Context, APInt(cast(CurTy)->getBitWidth(), NumWords, &Words[0])); break; @@ -985,14 +985,14 @@ bool BitcodeReader::ParseConstants() { V = UndefValue::get(CurTy); break; } - + case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] if (Record.empty()) return Error("Invalid CST_AGGREGATE record"); - + unsigned Size = Record.size(); std::vector Elts; - + if (const StructType *STy = dyn_cast(CurTy)) { for (unsigned i = 0; i != Size; ++i) Elts.push_back(ValueList.getConstantFwdRef(Record[i], @@ -1019,7 +1019,7 @@ bool BitcodeReader::ParseConstants() { const ArrayType *ATy = cast(CurTy); const Type *EltTy = ATy->getElementType(); - + unsigned Size = Record.size(); std::vector Elts; for (unsigned i = 0; i != Size; ++i) @@ -1030,10 +1030,10 @@ bool BitcodeReader::ParseConstants() { case bitc::CST_CODE_CSTRING: { // CSTRING: [values] if (Record.empty()) return Error("Invalid CST_AGGREGATE record"); - + const ArrayType *ATy = cast(CurTy); const Type *EltTy = ATy->getElementType(); - + unsigned Size = Record.size(); std::vector Elts; for (unsigned i = 0; i != Size; ++i) @@ -1067,7 +1067,7 @@ bool BitcodeReader::ParseConstants() { V = ConstantExpr::get(Opc, LHS, RHS, Flags); } break; - } + } case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] if (Record.size() < 3) return Error("Invalid CE_CAST record"); int Opc = GetDecodedCastOpcode(Record[0]); @@ -1080,7 +1080,7 @@ bool BitcodeReader::ParseConstants() { V = ConstantExpr::getCast(Opc, Op, CurTy); } break; - } + } case bitc::CST_CODE_CE_INBOUNDS_GEP: case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] if (Record.size() & 1) return Error("Invalid CE_GEP record"); @@ -1107,7 +1107,7 @@ bool BitcodeReader::ParseConstants() { break; case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); - const VectorType *OpTy = + const VectorType *OpTy = dyn_cast_or_null(getTypeByID(Record[0])); if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); @@ -1132,7 +1132,7 @@ bool BitcodeReader::ParseConstants() { return Error("Invalid CE_SHUFFLEVEC record"); Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); - const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), + const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), OpTy->getNumElements()); Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); @@ -1145,7 +1145,7 @@ bool BitcodeReader::ParseConstants() { return Error("Invalid CE_SHUFVEC_EX record"); Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); - const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), + const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), RTy->getNumElements()); Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); @@ -1174,7 +1174,7 @@ bool BitcodeReader::ParseConstants() { unsigned ConstStrSize = Record[2+AsmStrSize]; if (3+AsmStrSize+ConstStrSize > Record.size()) return Error("Invalid INLINEASM record"); - + for (unsigned i = 0; i != AsmStrSize; ++i) AsmStr += (char)Record[2+i]; for (unsigned i = 0; i != ConstStrSize; ++i) @@ -1185,17 +1185,17 @@ bool BitcodeReader::ParseConstants() { break; } } - + ValueList.AssignValue(V, NextCstNo); ++NextCstNo; } - + if (NextCstNo != ValueList.size()) return Error("Invalid constant reference!"); - + if (Stream.ReadBlockEnd()) return Error("Error at end of constants block"); - + // Once all the constants have been read, go through and resolve forward // references. ValueList.ResolveConstantForwardRefs(); @@ -1209,18 +1209,18 @@ bool BitcodeReader::RememberAndSkipFunctionBody() { // Get the function we are talking about. if (FunctionsWithBodies.empty()) return Error("Insufficient function protos"); - + Function *Fn = FunctionsWithBodies.back(); FunctionsWithBodies.pop_back(); - + // Save the current stream state. uint64_t CurBit = Stream.GetCurrentBitNo(); DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage()); - + // Set the functions linkage to GhostLinkage so we know it is lazily // deserialized. Fn->setLinkage(GlobalValue::GhostLinkage); - + // Skip over the function block for now. if (Stream.SkipBlock()) return Error("Malformed block record"); @@ -1231,13 +1231,13 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { // Reject multiple MODULE_BLOCK's in a single bitstream. if (TheModule) return Error("Multiple MODULE_BLOCKs in same stream"); - + if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) return Error("Malformed block record"); // Otherwise, create the module. TheModule = new Module(ModuleID, Context); - + SmallVector Record; std::vector SectionTable; std::vector GCTable; @@ -1271,7 +1271,7 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { std::vector().swap(FunctionsWithBodies); return false; } - + if (Code == bitc::ENTER_SUBBLOCK) { switch (Stream.ReadSubBlockID()) { default: // Skip unknown content. @@ -1313,19 +1313,19 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); HasReversedFunctionsWithBodies = true; } - + if (RememberAndSkipFunctionBody()) return true; break; } continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. switch (Stream.ReadRecord(Code, Record)) { default: break; // Default behavior, ignore unknown content. @@ -1388,7 +1388,7 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { return Error("Global not a pointer type!"); unsigned AddressSpace = cast(Ty)->getAddressSpace(); Ty = cast(Ty)->getElementType(); - + bool isConstant = Record[1]; GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); unsigned Alignment = (1 << Record[4]) >> 1; @@ -1406,16 +1406,16 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { isThreadLocal = Record[7]; GlobalVariable *NewGV = - new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, + new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, isThreadLocal, AddressSpace); NewGV->setAlignment(Alignment); if (!Section.empty()) NewGV->setSection(Section); NewGV->setVisibility(Visibility); NewGV->setThreadLocal(isThreadLocal); - + ValueList.push_back(NewGV); - + // Remember which value to use for the global initializer. if (unsigned InitID = Record[2]) GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); @@ -1441,7 +1441,7 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { bool isProto = Record[2]; Func->setLinkage(GetDecodedLinkage(Record[3])); Func->setAttributes(getAttributes(Record[4])); - + Func->setAlignment((1 << Record[5]) >> 1); if (Record[6]) { if (Record[6]-1 >= SectionTable.size()) @@ -1455,7 +1455,7 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { Func->setGC(GCTable[Record[8]-1].c_str()); } ValueList.push_back(Func); - + // If this is a function with a body, remember the prototype we are // creating now, so that we can match up the body with them later. if (!isProto) @@ -1470,7 +1470,7 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { const Type *Ty = getTypeByID(Record[0]); if (!isa(Ty)) return Error("Function not a pointer type!"); - + GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), "", 0, TheModule); // Old bitcode files didn't have visibility field. @@ -1490,28 +1490,28 @@ bool BitcodeReader::ParseModule(const std::string &ModuleID) { } Record.clear(); } - + return Error("Premature end of bitstream"); } bool BitcodeReader::ParseBitcode() { TheModule = 0; - + if (Buffer->getBufferSize() & 3) return Error("Bitcode stream should be a multiple of 4 bytes in length"); - + unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart(); unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); - + // If we have a wrapper header, parse it and ignore the non-bc file contents. // The magic number is 0x0B17C0DE stored in little endian. if (isBitcodeWrapper(BufPtr, BufEnd)) if (SkipBitcodeWrapperHeader(BufPtr, BufEnd)) return Error("Invalid bitcode wrapper header"); - + StreamFile.init(BufPtr, BufEnd); Stream.init(StreamFile); - + // Sniff for the signature. if (Stream.Read(8) != 'B' || Stream.Read(8) != 'C' || @@ -1520,17 +1520,17 @@ bool BitcodeReader::ParseBitcode() { Stream.Read(4) != 0xE || Stream.Read(4) != 0xD) return Error("Invalid bitcode signature"); - + // We expect a number of well-defined blocks, though we don't necessarily // need to understand them all. while (!Stream.AtEndOfStream()) { unsigned Code = Stream.ReadCode(); - + if (Code != bitc::ENTER_SUBBLOCK) return Error("Invalid record at top-level"); - + unsigned BlockID = Stream.ReadSubBlockID(); - + // We only know the MODULE subblock ID. switch (BlockID) { case bitc::BLOCKINFO_BLOCK_ID: @@ -1547,7 +1547,7 @@ bool BitcodeReader::ParseBitcode() { break; } } - + return false; } @@ -1555,14 +1555,14 @@ bool BitcodeReader::ParseBitcode() { bool BitcodeReader::ParseMetadataAttachment() { if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) return Error("Malformed block record"); - + Metadata &TheMetadata = Context.getMetadata(); SmallVector Record; while(1) { unsigned Code = Stream.ReadCode(); if (Code == bitc::END_BLOCK) { if (Stream.ReadBlockEnd()) - return Error("Error at end of PARAMATTR block"); + return Error("Error at end of PARAMATTR block"); break; } if (Code == bitc::DEFINE_ABBREV) { @@ -1577,12 +1577,12 @@ bool BitcodeReader::ParseMetadataAttachment() { case bitc::METADATA_ATTACHMENT: { unsigned RecordLength = Record.size(); if (Record.empty() || (RecordLength - 1) % 2 == 1) - return Error ("Invalid METADATA_ATTACHMENT reader!"); + return Error ("Invalid METADATA_ATTACHMENT reader!"); Instruction *Inst = InstructionList[Record[0]]; for (unsigned i = 1; i != RecordLength; i = i+2) { - MDKindID Kind = Record[i]; - Value *Node = MDValueList.getValueFwdRef(Record[i+1]); - TheMetadata.setMD(Kind, cast(Node), Inst); + MDKindID Kind = Record[i]; + Value *Node = MDValueList.getValueFwdRef(Record[i+1]); + TheMetadata.setMD(Kind, cast(Node), Inst); } break; } @@ -1595,13 +1595,13 @@ bool BitcodeReader::ParseMetadataAttachment() { bool BitcodeReader::ParseFunctionBody(Function *F) { if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) return Error("Malformed block record"); - + unsigned ModuleValueListSize = ValueList.size(); - + // Add all the function arguments to the value table. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) ValueList.push_back(I); - + unsigned NextValueNo = ValueList.size(); BasicBlock *CurBB = 0; unsigned CurBBNo = 0; @@ -1615,7 +1615,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { return Error("Error at end of function block"); break; } - + if (Code == bitc::ENTER_SUBBLOCK) { switch (Stream.ReadSubBlockID()) { default: // Skip unknown content. @@ -1630,17 +1630,17 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { if (ParseValueSymbolTable()) return true; break; case bitc::METADATA_ATTACHMENT_ID: - if (ParseMetadataAttachment()) return true; - break; + if (ParseMetadataAttachment()) return true; + break; } continue; } - + if (Code == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } - + // Read a record. Record.clear(); Instruction *I = 0; @@ -1657,7 +1657,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { FunctionBBs[i] = BasicBlock::Create(Context, "", F); CurBB = FunctionBBs[0]; continue; - + case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] unsigned OpNum = 0; Value *LHS, *RHS; @@ -1665,7 +1665,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { getValue(Record, OpNum, LHS->getType(), RHS) || OpNum+1 > Record.size()) return Error("Invalid BINOP record"); - + int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); if (Opc == -1) return Error("Invalid BINOP record"); I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); @@ -1691,7 +1691,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { if (getValueTypePair(Record, OpNum, NextValueNo, Op) || OpNum+2 != Record.size()) return Error("Invalid CAST record"); - + const Type *ResTy = getTypeByID(Record[OpNum]); int Opc = GetDecodedCastOpcode(Record[OpNum+1]); if (Opc == -1 || ResTy == 0) @@ -1721,7 +1721,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { cast(I)->setIsInBounds(true); break; } - + case bitc::FUNC_CODE_INST_EXTRACTVAL: { // EXTRACTVAL: [opty, opval, n x indices] unsigned OpNum = 0; @@ -1743,7 +1743,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { InstructionList.push_back(I); break; } - + case bitc::FUNC_CODE_INST_INSERTVAL: { // INSERTVAL: [opty, opval, opty, opval, n x indices] unsigned OpNum = 0; @@ -1768,7 +1768,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { InstructionList.push_back(I); break; } - + case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] // obsolete form of select // handles select i1 ... in old bitcode @@ -1778,12 +1778,12 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { getValue(Record, OpNum, TrueVal->getType(), FalseVal) || getValue(Record, OpNum, Type::getInt1Ty(Context), Cond)) return Error("Invalid SELECT record"); - + I = SelectInst::Create(Cond, TrueVal, FalseVal); InstructionList.push_back(I); break; } - + case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] // new form of select // handles select i1 or select [N x i1] @@ -1798,19 +1798,19 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { if (const VectorType* vector_type = dyn_cast(Cond->getType())) { // expect - if (vector_type->getElementType() != Type::getInt1Ty(Context)) + if (vector_type->getElementType() != Type::getInt1Ty(Context)) return Error("Invalid SELECT condition type"); } else { // expect i1 - if (Cond->getType() != Type::getInt1Ty(Context)) + if (Cond->getType() != Type::getInt1Ty(Context)) return Error("Invalid SELECT condition type"); - } - + } + I = SelectInst::Create(Cond, TrueVal, FalseVal); InstructionList.push_back(I); break; } - + case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] unsigned OpNum = 0; Value *Vec, *Idx; @@ -1821,12 +1821,12 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { InstructionList.push_back(I); break; } - + case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] unsigned OpNum = 0; Value *Vec, *Elt, *Idx; if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || - getValue(Record, OpNum, + getValue(Record, OpNum, cast(Vec->getType())->getElementType(), Elt) || getValue(Record, OpNum, Type::getInt32Ty(Context), Idx)) return Error("Invalid INSERTELT record"); @@ -1834,7 +1834,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { InstructionList.push_back(I); break; } - + case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] unsigned OpNum = 0; Value *Vec1, *Vec2, *Mask; @@ -1862,7 +1862,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { getValue(Record, OpNum, LHS->getType(), RHS) || OpNum+1 != Record.size()) return Error("Invalid CMP record"); - + if (LHS->getType()->isFPOrFPVector()) I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); else @@ -1882,13 +1882,13 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { InstructionList.push_back(I); break; } - + case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval] { unsigned Size = Record.size(); if (Size == 0) { I = ReturnInst::Create(Context); - InstructionList.push_back(I); + InstructionList.push_back(I); break; } @@ -1908,18 +1908,18 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { Value *RV = UndefValue::get(ReturnType); for (unsigned i = 0, e = Vs.size(); i != e; ++i) { I = InsertValueInst::Create(RV, Vs[i], i, "mrv"); - InstructionList.push_back(I); + InstructionList.push_back(I); CurBB->getInstList().push_back(I); ValueList.AssignValue(I, NextValueNo++); RV = I; } I = ReturnInst::Create(Context, RV); - InstructionList.push_back(I); + InstructionList.push_back(I); break; } I = ReturnInst::Create(Context, Vs[0]); - InstructionList.push_back(I); + InstructionList.push_back(I); break; } case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] @@ -1931,7 +1931,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { if (Record.size() == 1) { I = BranchInst::Create(TrueDest); - InstructionList.push_back(I); + InstructionList.push_back(I); } else { BasicBlock *FalseDest = getBasicBlock(Record[1]); @@ -1939,7 +1939,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { if (FalseDest == 0 || Cond == 0) return Error("Invalid BR record"); I = BranchInst::Create(TrueDest, FalseDest, Cond); - InstructionList.push_back(I); + InstructionList.push_back(I); } break; } @@ -1955,7 +1955,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); InstructionList.push_back(SI); for (unsigned i = 0, e = NumCases; i != e; ++i) { - ConstantInt *CaseVal = + ConstantInt *CaseVal = dyn_cast_or_null(getFnValueByID(Record[3+i*2], OpTy)); BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); if (CaseVal == 0 || DestBB == 0) { @@ -1967,7 +1967,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { I = SI; break; } - + case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] if (Record.size() < 4) return Error("Invalid INVOKE record"); @@ -1975,12 +1975,12 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { unsigned CCInfo = Record[1]; BasicBlock *NormalBB = getBasicBlock(Record[2]); BasicBlock *UnwindBB = getBasicBlock(Record[3]); - + unsigned OpNum = 4; Value *Callee; if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) return Error("Invalid INVOKE record"); - + const PointerType *CalleeTy = dyn_cast(Callee->getType()); const FunctionType *FTy = !CalleeTy ? 0 : dyn_cast(CalleeTy->getElementType()); @@ -1989,13 +1989,13 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || Record.size() < OpNum+FTy->getNumParams()) return Error("Invalid INVOKE record"); - + SmallVector Ops; for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); if (Ops.back() == 0) return Error("Invalid INVOKE record"); } - + if (!FTy->isVarArg()) { if (Record.size() != OpNum) return Error("Invalid INVOKE record"); @@ -2008,7 +2008,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { Ops.push_back(Op); } } - + I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end()); InstructionList.push_back(I); @@ -2030,11 +2030,11 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { return Error("Invalid PHI record"); const Type *Ty = getTypeByID(Record[0]); if (!Ty) return Error("Invalid PHI record"); - + PHINode *PN = PHINode::Create(Ty); InstructionList.push_back(PN); PN->reserveOperandSpace((Record.size()-1)/2); - + for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { Value *V = getFnValueByID(Record[1+i], Ty); BasicBlock *BB = getBasicBlock(Record[2+i]); @@ -2044,7 +2044,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { I = PN; break; } - + case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align] if (Record.size() < 3) return Error("Invalid MALLOC record"); @@ -2085,7 +2085,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { if (getValueTypePair(Record, OpNum, NextValueNo, Op) || OpNum+2 != Record.size()) return Error("Invalid LOAD record"); - + I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); InstructionList.push_back(I); break; @@ -2094,11 +2094,11 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { unsigned OpNum = 0; Value *Val, *Ptr; if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || - getValue(Record, OpNum, + getValue(Record, OpNum, cast(Ptr->getType())->getElementType(), Val) || OpNum+2 != Record.size()) return Error("Invalid STORE record"); - + I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); InstructionList.push_back(I); break; @@ -2108,11 +2108,11 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { unsigned OpNum = 0; Value *Val, *Ptr; if (getValueTypePair(Record, OpNum, NextValueNo, Val) || - getValue(Record, OpNum, + getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)|| OpNum+2 != Record.size()) return Error("Invalid STORE record"); - + I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); InstructionList.push_back(I); break; @@ -2121,21 +2121,21 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] if (Record.size() < 3) return Error("Invalid CALL record"); - + AttrListPtr PAL = getAttributes(Record[0]); unsigned CCInfo = Record[1]; - + unsigned OpNum = 2; Value *Callee; if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) return Error("Invalid CALL record"); - + const PointerType *OpTy = dyn_cast(Callee->getType()); const FunctionType *FTy = 0; if (OpTy) FTy = dyn_cast(OpTy->getElementType()); if (!FTy || Record.size() < FTy->getNumParams()+OpNum) return Error("Invalid CALL record"); - + SmallVector Args; // Read the fixed params. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { @@ -2145,7 +2145,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); if (Args.back() == 0) return Error("Invalid CALL record"); } - + // Read type/value pairs for varargs params. if (!FTy->isVarArg()) { if (OpNum != Record.size()) @@ -2158,7 +2158,7 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { Args.push_back(Op); } } - + I = CallInst::Create(Callee, Args.begin(), Args.end()); InstructionList.push_back(I); cast(I)->setCallingConv( @@ -2188,18 +2188,18 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { return Error("Invalid instruction with no BB"); } CurBB->getInstList().push_back(I); - + // If this was a terminator instruction, move to the next block. if (isa(I)) { ++CurBBNo; CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; } - + // Non-void values get registered in the value table for future use. if (I && I->getType() != Type::getVoidTy(Context)) ValueList.AssignValue(I, NextValueNo++); } - + // Check the function list for unresolved values. if (Argument *A = dyn_cast(ValueList.back())) { if (A->getParent() == 0) { @@ -2213,11 +2213,11 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { return Error("Never resolved value found in function!"); } } - + // Trim the value list down to the size it was before we parsed this function. ValueList.shrinkTo(ModuleValueListSize); std::vector().swap(FunctionBBs); - + return false; } @@ -2229,16 +2229,16 @@ bool BitcodeReader::ParseFunctionBody(Function *F) { bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) { // If it already is material, ignore the request. if (!F->hasNotBeenReadFromBitcode()) return false; - - DenseMap >::iterator DFII = + + DenseMap >::iterator DFII = DeferredFunctionInfo.find(F); assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); - + // Move the bit stream to the saved position of the deferred function body and // restore the real linkage type for the function. Stream.JumpToBit(DFII->second.first); F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second); - + if (ParseFunctionBody(F)) { if (ErrInfo) *ErrInfo = ErrorString; return true; @@ -2255,7 +2255,7 @@ bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) { } } } - + return false; } @@ -2263,9 +2263,9 @@ void BitcodeReader::dematerializeFunction(Function *F) { // If this function isn't materialized, or if it is a proto, this is a noop. if (F->hasNotBeenReadFromBitcode() || F->isDeclaration()) return; - + assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); - + // Just forget the function body, we can remat it later. F->deleteBody(); F->setLinkage(GlobalValue::GhostLinkage); @@ -2281,9 +2281,9 @@ Module *BitcodeReader::materializeModule(std::string *ErrInfo) { materializeFunction(F, ErrInfo)) return 0; - // Upgrade any intrinsic calls that slipped through (should not happen!) and - // delete the old functions to clean up. We can't do this unless the entire - // module is materialized because there could always be another function body + // Upgrade any intrinsic calls that slipped through (should not happen!) and + // delete the old functions to clean up. We can't do this unless the entire + // module is materialized because there could always be another function body // with calls to the old function. for (std::vector >::iterator I = UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { @@ -2332,7 +2332,7 @@ ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer, if (R->ParseBitcode()) { if (ErrMsg) *ErrMsg = R->getErrorString(); - + // Don't let the BitcodeReader dtor delete 'Buffer'. R->releaseMemoryBuffer(); delete R; @@ -2343,25 +2343,25 @@ ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer, /// ParseBitcodeFile - Read the specified bitcode file, returning the module. /// If an error occurs, return null and fill in *ErrMsg if non-null. -Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, +Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, std::string *ErrMsg){ BitcodeReader *R; - R = static_cast(getBitcodeModuleProvider(Buffer, Context, + R = static_cast(getBitcodeModuleProvider(Buffer, Context, ErrMsg)); if (!R) return 0; - + // Read in the entire module. Module *M = R->materializeModule(ErrMsg); // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether // there was an error. R->releaseMemoryBuffer(); - + // If there was no error, tell ModuleProvider not to delete it when its dtor // is run. if (M) M = R->releaseModule(ErrMsg); - + delete R; return M; } diff --git a/lib/Bitcode/Writer/BitcodeWriter.cpp b/lib/Bitcode/Writer/BitcodeWriter.cpp index 3d89f3d0f00..3511dbc96ca 100644 --- a/lib/Bitcode/Writer/BitcodeWriter.cpp +++ b/lib/Bitcode/Writer/BitcodeWriter.cpp @@ -34,19 +34,19 @@ using namespace llvm; /// be kept in sync with the reader, but need to be consistent within this file. enum { CurVersion = 0, - + // VALUE_SYMTAB_BLOCK abbrev id's. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, VST_ENTRY_7_ABBREV, VST_ENTRY_6_ABBREV, VST_BBENTRY_6_ABBREV, - + // CONSTANTS_BLOCK abbrev id's. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, CONSTANTS_INTEGER_ABBREV, CONSTANTS_CE_CAST_Abbrev, CONSTANTS_NULL_Abbrev, - + // FUNCTION_BLOCK abbrev id's. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, FUNCTION_INST_BINOP_ABBREV, @@ -102,24 +102,24 @@ static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { -static void WriteStringRecord(unsigned Code, const std::string &Str, +static void WriteStringRecord(unsigned Code, const std::string &Str, unsigned AbbrevToUse, BitstreamWriter &Stream) { SmallVector Vals; - + // Code: [strchar x N] for (unsigned i = 0, e = Str.size(); i != e; ++i) Vals.push_back(Str[i]); - + // Emit the finished record. Stream.EmitRecord(Code, Vals, AbbrevToUse); } // Emit information about parameter attributes. -static void WriteAttributeTable(const ValueEnumerator &VE, +static void WriteAttributeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { const std::vector &Attrs = VE.getAttributes(); if (Attrs.empty()) return; - + Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); SmallVector Record; @@ -140,21 +140,21 @@ static void WriteAttributeTable(const ValueEnumerator &VE, Record.push_back(FauxAttr); } - + Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); Record.clear(); } - + Stream.ExitBlock(); } /// WriteTypeTable - Write out the type table for a module. static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { const ValueEnumerator::TypeList &TypeList = VE.getTypes(); - + Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */); SmallVector TypeVals; - + // Abbrev for TYPE_CODE_POINTER. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); @@ -162,7 +162,7 @@ static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { Log2_32_Ceil(VE.getTypes().size()+1))); Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv); - + // Abbrev for TYPE_CODE_FUNCTION. Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); @@ -172,7 +172,7 @@ static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(VE.getTypes().size()+1))); unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); - + // Abbrev for TYPE_CODE_STRUCT. Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT)); @@ -181,7 +181,7 @@ static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(VE.getTypes().size()+1))); unsigned StructAbbrev = Stream.EmitAbbrev(Abbv); - + // Abbrev for TYPE_CODE_ARRAY. Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); @@ -189,18 +189,18 @@ static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(VE.getTypes().size()+1))); unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); - + // Emit an entry count so the reader can reserve space. TypeVals.push_back(TypeList.size()); Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); TypeVals.clear(); - + // Loop over all of the types, emitting each in turn. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { const Type *T = TypeList[i].first; int AbbrevToUse = 0; unsigned Code = 0; - + switch (T->getTypeID()) { default: llvm_unreachable("Unknown type!"); case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; @@ -274,7 +274,7 @@ static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { Stream.EmitRecord(Code, TypeVals, AbbrevToUse); TypeVals.clear(); } - + Stream.ExitBlock(); } @@ -337,7 +337,7 @@ static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, GV != E; ++GV) { MaxAlignment = std::max(MaxAlignment, GV->getAlignment()); MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType())); - + if (!GV->hasSection()) continue; // Give section names unique ID's. unsigned &Entry = SectionMap[GV->getSection()]; @@ -367,10 +367,10 @@ static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, } } } - + // Emit abbrev for globals, now that we know # sections and max alignment. unsigned SimpleGVarAbbrev = 0; - if (!M->global_empty()) { + if (!M->global_empty()) { // Add an abbrev for common globals with no visibility or thread localness. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); @@ -394,14 +394,14 @@ static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, // Don't bother emitting vis + thread local. SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); } - + // Emit the global variable information. SmallVector Vals; for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); GV != E; ++GV) { unsigned AbbrevToUse = 0; - // GLOBALVAR: [type, isconst, initid, + // GLOBALVAR: [type, isconst, initid, // linkage, alignment, section, visibility, threadlocal] Vals.push_back(VE.getTypeID(GV->getType())); Vals.push_back(GV->isConstant()); @@ -410,14 +410,14 @@ static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, Vals.push_back(getEncodedLinkage(GV)); Vals.push_back(Log2_32(GV->getAlignment())+1); Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0); - if (GV->isThreadLocal() || + if (GV->isThreadLocal() || GV->getVisibility() != GlobalValue::DefaultVisibility) { Vals.push_back(getEncodedVisibility(GV)); Vals.push_back(GV->isThreadLocal()); } else { AbbrevToUse = SimpleGVarAbbrev; } - + Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); Vals.clear(); } @@ -435,13 +435,13 @@ static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0); Vals.push_back(getEncodedVisibility(F)); Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0); - + unsigned AbbrevToUse = 0; Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); Vals.clear(); } - - + + // Emit the alias information. for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); AI != E; ++AI) { @@ -496,7 +496,7 @@ static void WriteModuleMetadata(const ValueEnumerator &VE, unsigned MDSAbbrev = 0; SmallVector Record; for (unsigned i = 0, e = Vals.size(); i != e; ++i) { - + if (const MDNode *N = dyn_cast(Vals[i].first)) { if (!StartedMetadataBlock) { Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); @@ -506,7 +506,7 @@ static void WriteModuleMetadata(const ValueEnumerator &VE, } else if (const MDString *MDS = dyn_cast(Vals[i].first)) { if (!StartedMetadataBlock) { Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); - + // Abbrev for METADATA_STRING. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING)); @@ -515,12 +515,12 @@ static void WriteModuleMetadata(const ValueEnumerator &VE, MDSAbbrev = Stream.EmitAbbrev(Abbv); StartedMetadataBlock = true; } - + // Code: [strchar x N] const char *StrBegin = MDS->begin(); for (unsigned i = 0, e = MDS->length(); i != e; ++i) Record.push_back(StrBegin[i]); - + // Emit the finished record. Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev); Record.clear(); @@ -540,26 +540,26 @@ static void WriteModuleMetadata(const ValueEnumerator &VE, // Write named metadata elements. for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { - if (NMD->getElement(i)) + if (NMD->getElement(i)) Record.push_back(VE.getValueID(NMD->getElement(i))); - else + else Record.push_back(0); } Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); Record.clear(); } } - + if (StartedMetadataBlock) Stream.ExitBlock(); } static void WriteMetadataAttachment(const Function &F, - const ValueEnumerator &VE, - BitstreamWriter &Stream) { + const ValueEnumerator &VE, + BitstreamWriter &Stream) { bool StartedMetadataBlock = false; SmallVector Record; - + // Write metadata attachments // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] Metadata &TheMetadata = F.getContext().getMetadata(); @@ -570,41 +570,41 @@ static void WriteMetadataAttachment(const Function &F, if (!P) continue; bool RecordedInstruction = false; for (Metadata::MDMapTy::const_iterator PI = P->begin(), PE = P->end(); - PI != PE; ++PI) { - if (MDNode *ND = dyn_cast_or_null(PI->second)) { - if (RecordedInstruction == false) { - Record.push_back(VE.getInstructionID(I)); - RecordedInstruction = true; - } - Record.push_back(PI->first); - Record.push_back(VE.getValueID(ND)); - } + PI != PE; ++PI) { + if (MDNode *ND = dyn_cast_or_null(PI->second)) { + if (RecordedInstruction == false) { + Record.push_back(VE.getInstructionID(I)); + RecordedInstruction = true; + } + Record.push_back(PI->first); + Record.push_back(VE.getValueID(ND)); + } } if (!StartedMetadataBlock) { - Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); - StartedMetadataBlock = true; + Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); + StartedMetadataBlock = true; } Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); Record.clear(); } - if (StartedMetadataBlock) + if (StartedMetadataBlock) Stream.ExitBlock(); } static void WriteModuleMetadataStore(const Module *M, - const ValueEnumerator &VE, - BitstreamWriter &Stream) { - + const ValueEnumerator &VE, + BitstreamWriter &Stream) { + bool StartedMetadataBlock = false; SmallVector Record; - + // Write metadata kinds // METADATA_KIND - [n x [id, name]] Metadata &TheMetadata = M->getContext().getMetadata(); const StringMap *Kinds = TheMetadata.getHandlerNames(); - for (StringMap::const_iterator - I = Kinds->begin(), E = Kinds->end(); I != E; ++I) { + for (StringMap::const_iterator + I = Kinds->begin(), E = Kinds->end(); I != E; ++I) { Record.push_back(I->second); StringRef KName = I->first(); for (unsigned i = 0, e = KName.size(); i != e; ++i) @@ -617,7 +617,7 @@ static void WriteModuleMetadataStore(const Module *M, Record.clear(); } - if (StartedMetadataBlock) + if (StartedMetadataBlock) Stream.ExitBlock(); } @@ -625,7 +625,7 @@ static void WriteConstants(unsigned FirstVal, unsigned LastVal, const ValueEnumerator &VE, BitstreamWriter &Stream, bool isGlobal) { if (FirstVal == LastVal) return; - + Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); unsigned AggregateAbbrev = 0; @@ -659,8 +659,8 @@ static void WriteConstants(unsigned FirstVal, unsigned LastVal, Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); CString6Abbrev = Stream.EmitAbbrev(Abbv); - } - + } + SmallVector Record; const ValueEnumerator::ValueList &Vals = VE.getValues(); @@ -675,16 +675,16 @@ static void WriteConstants(unsigned FirstVal, unsigned LastVal, CONSTANTS_SETTYPE_ABBREV); Record.clear(); } - + if (const InlineAsm *IA = dyn_cast(V)) { Record.push_back(unsigned(IA->hasSideEffects())); - + // Add the asm string. const std::string &AsmStr = IA->getAsmString(); Record.push_back(AsmStr.size()); for (unsigned i = 0, e = AsmStr.size(); i != e; ++i) Record.push_back(AsmStr[i]); - + // Add the constraint string. const std::string &ConstraintStr = IA->getConstraintString(); Record.push_back(ConstraintStr.size()); @@ -711,11 +711,11 @@ static void WriteConstants(unsigned FirstVal, unsigned LastVal, Code = bitc::CST_CODE_INTEGER; AbbrevToUse = CONSTANTS_INTEGER_ABBREV; } else { // Wide integers, > 64 bits in size. - // We have an arbitrary precision integer value to write whose - // bit width is > 64. However, in canonical unsigned integer + // We have an arbitrary precision integer value to write whose + // bit width is > 64. However, in canonical unsigned integer // format it is likely that the high bits are going to be zero. // So, we only write the number of active words. - unsigned NWords = IV->getValue().getActiveWords(); + unsigned NWords = IV->getValue().getActiveWords(); const uint64_t *RawWords = IV->getValue().getRawData(); for (unsigned i = 0; i != NWords; ++i) { int64_t V = RawWords[i]; @@ -765,10 +765,10 @@ static void WriteConstants(unsigned FirstVal, unsigned LastVal, unsigned char V = cast(C->getOperand(i))->getZExtValue(); Record.push_back(V); isCStr7 &= (V & 128) == 0; - if (isCStrChar6) + if (isCStrChar6) isCStrChar6 = BitCodeAbbrevOp::isChar6(V); } - + if (isCStrChar6) AbbrevToUse = CString6Abbrev; else if (isCStr7) @@ -863,7 +863,7 @@ static void WriteConstants(unsigned FirstVal, unsigned LastVal, static void WriteModuleConstants(const ValueEnumerator &VE, BitstreamWriter &Stream) { const ValueEnumerator::ValueList &Vals = VE.getValues(); - + // Find the first constant to emit, which is the first non-globalvalue value. // We know globalvalues have been emitted by WriteModuleInfo. for (unsigned i = 0, e = Vals.size(); i != e; ++i) { @@ -883,7 +883,7 @@ static void WriteModuleConstants(const ValueEnumerator &VE, /// instruction ID, then it is a forward reference, and it also includes the /// type ID. static bool PushValueAndType(const Value *V, unsigned InstID, - SmallVector &Vals, + SmallVector &Vals, ValueEnumerator &VE) { unsigned ValID = VE.getValueID(V); Vals.push_back(ValID); @@ -981,7 +981,7 @@ static void WriteInstruction(const Instruction &I, unsigned InstID, Vals.push_back(cast(I).getPredicate()); break; - case Instruction::Ret: + case Instruction::Ret: { Code = bitc::FUNC_CODE_INST_RET; unsigned NumOperands = I.getNumOperands(); @@ -1019,13 +1019,13 @@ static void WriteInstruction(const Instruction &I, unsigned InstID, const PointerType *PTy = cast(Callee->getType()); const FunctionType *FTy = cast(PTy->getElementType()); Code = bitc::FUNC_CODE_INST_INVOKE; - + Vals.push_back(VE.getAttributeID(II->getAttributes())); Vals.push_back(II->getCallingConv()); Vals.push_back(VE.getValueID(II->getNormalDest())); Vals.push_back(VE.getValueID(II->getUnwindDest())); PushValueAndType(Callee, InstID, Vals, VE); - + // Emit value #'s for the fixed parameters. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param. @@ -1045,38 +1045,38 @@ static void WriteInstruction(const Instruction &I, unsigned InstID, Code = bitc::FUNC_CODE_INST_UNREACHABLE; AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; break; - + case Instruction::PHI: Code = bitc::FUNC_CODE_INST_PHI; Vals.push_back(VE.getTypeID(I.getType())); for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) Vals.push_back(VE.getValueID(I.getOperand(i))); break; - + case Instruction::Malloc: Code = bitc::FUNC_CODE_INST_MALLOC; Vals.push_back(VE.getTypeID(I.getType())); Vals.push_back(VE.getValueID(I.getOperand(0))); // size. Vals.push_back(Log2_32(cast(I).getAlignment())+1); break; - + case Instruction::Free: Code = bitc::FUNC_CODE_INST_FREE; PushValueAndType(I.getOperand(0), InstID, Vals, VE); break; - + case Instruction::Alloca: Code = bitc::FUNC_CODE_INST_ALLOCA; Vals.push_back(VE.getTypeID(I.getType())); Vals.push_back(VE.getValueID(I.getOperand(0))); // size. Vals.push_back(Log2_32(cast(I).getAlignment())+1); break; - + case Instruction::Load: Code = bitc::FUNC_CODE_INST_LOAD; if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; - + Vals.push_back(Log2_32(cast(I).getAlignment())+1); Vals.push_back(cast(I).isVolatile()); break; @@ -1092,16 +1092,16 @@ static void WriteInstruction(const Instruction &I, unsigned InstID, const FunctionType *FTy = cast(PTy->getElementType()); Code = bitc::FUNC_CODE_INST_CALL; - + const CallInst *CI = cast(&I); Vals.push_back(VE.getAttributeID(CI->getAttributes())); Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall())); PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee - + // Emit value #'s for the fixed parameters. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param. - + // Emit type/value pairs for varargs params. if (FTy->isVarArg()) { unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams(); @@ -1118,7 +1118,7 @@ static void WriteInstruction(const Instruction &I, unsigned InstID, Vals.push_back(VE.getTypeID(I.getType())); // restype. break; } - + Stream.EmitRecord(Code, Vals, AbbrevToUse); Vals.clear(); } @@ -1133,27 +1133,27 @@ static void WriteValueSymbolTable(const ValueSymbolTable &VST, // FIXME: Set up the abbrev, we know how many values there are! // FIXME: We know if the type names can use 7-bit ascii. SmallVector NameVals; - + for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); SI != SE; ++SI) { - + const ValueName &Name = *SI; - + // Figure out the encoding to use for the name. bool is7Bit = true; bool isChar6 = true; for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength(); C != E; ++C) { - if (isChar6) + if (isChar6) isChar6 = BitCodeAbbrevOp::isChar6(*C); if ((unsigned char)*C & 128) { is7Bit = false; break; // don't bother scanning the rest. } } - + unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; - + // VST_ENTRY: [valueid, namechar x N] // VST_BBENTRY: [bbid, namechar x N] unsigned Code; @@ -1168,12 +1168,12 @@ static void WriteValueSymbolTable(const ValueSymbolTable &VST, else if (is7Bit) AbbrevToUse = VST_ENTRY_7_ABBREV; } - + NameVals.push_back(VE.getValueID(SI->getValue())); for (const char *P = Name.getKeyData(), *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P) NameVals.push_back((unsigned char)*P); - + // Emit the finished record. Stream.EmitRecord(Code, NameVals, AbbrevToUse); NameVals.clear(); @@ -1182,27 +1182,27 @@ static void WriteValueSymbolTable(const ValueSymbolTable &VST, } /// WriteFunction - Emit a function body to the module stream. -static void WriteFunction(const Function &F, ValueEnumerator &VE, +static void WriteFunction(const Function &F, ValueEnumerator &VE, BitstreamWriter &Stream) { Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); VE.incorporateFunction(F); SmallVector Vals; - + // Emit the number of basic blocks, so the reader can create them ahead of // time. Vals.push_back(VE.getBasicBlocks().size()); Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); Vals.clear(); - + // If there are function-local constants, emit them now. unsigned CstStart, CstEnd; VE.getFunctionConstantRange(CstStart, CstEnd); WriteConstants(CstStart, CstEnd, VE, Stream, false); - - // Keep a running idea of what the instruction ID is. + + // Keep a running idea of what the instruction ID is. unsigned InstID = CstEnd; - + // Finally, emit all the instructions, in order. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); @@ -1211,7 +1211,7 @@ static void WriteFunction(const Function &F, ValueEnumerator &VE, if (I->getType() != Type::getVoidTy(F.getContext())) ++InstID; } - + // Emit names for all the instructions etc. WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); @@ -1225,9 +1225,9 @@ static void WriteTypeSymbolTable(const TypeSymbolTable &TST, const ValueEnumerator &VE, BitstreamWriter &Stream) { if (TST.empty()) return; - + Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3); - + // 7-bit fixed width VST_CODE_ENTRY strings. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); @@ -1236,14 +1236,14 @@ static void WriteTypeSymbolTable(const TypeSymbolTable &TST, Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); unsigned V7Abbrev = Stream.EmitAbbrev(Abbv); - + SmallVector NameVals; - - for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); + + for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); TI != TE; ++TI) { // TST_ENTRY: [typeid, namechar x N] NameVals.push_back(VE.getTypeID(TI->second)); - + const std::string &Str = TI->first; bool is7Bit = true; for (unsigned i = 0, e = Str.size(); i != e; ++i) { @@ -1251,12 +1251,12 @@ static void WriteTypeSymbolTable(const TypeSymbolTable &TST, if (Str[i] & 128) is7Bit = false; } - + // Emit the finished record. Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0); NameVals.clear(); } - + Stream.ExitBlock(); } @@ -1266,18 +1266,18 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other // blocks can defined their abbrevs inline. Stream.EnterBlockInfoBlock(2); - + { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); - if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, + if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != VST_ENTRY_8_ABBREV) llvm_unreachable("Unexpected abbrev ordering!"); } - + { // 7-bit fixed width VST_ENTRY strings. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); @@ -1308,9 +1308,9 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv) != VST_BBENTRY_6_ABBREV) llvm_unreachable("Unexpected abbrev ordering!"); } - - - + + + { // SETTYPE abbrev for CONSTANTS_BLOCK. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); @@ -1320,7 +1320,7 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv) != CONSTANTS_SETTYPE_ABBREV) llvm_unreachable("Unexpected abbrev ordering!"); } - + { // INTEGER abbrev for CONSTANTS_BLOCK. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); @@ -1329,7 +1329,7 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv) != CONSTANTS_INTEGER_ABBREV) llvm_unreachable("Unexpected abbrev ordering!"); } - + { // CE_CAST abbrev for CONSTANTS_BLOCK. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); @@ -1349,9 +1349,9 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv) != CONSTANTS_NULL_Abbrev) llvm_unreachable("Unexpected abbrev ordering!"); } - + // FIXME: This should only use space for first class types! - + { // INST_LOAD abbrev for FUNCTION_BLOCK. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); @@ -1394,7 +1394,7 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv) != FUNCTION_INST_CAST_ABBREV) llvm_unreachable("Unexpected abbrev ordering!"); } - + { // INST_RET abbrev for FUNCTION_BLOCK. BitCodeAbbrev *Abbv = new BitCodeAbbrev(); Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); @@ -1417,7 +1417,7 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV) llvm_unreachable("Unexpected abbrev ordering!"); } - + Stream.ExitBlock(); } @@ -1425,26 +1425,26 @@ static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { /// WriteModule - Emit the specified module to the bitstream. static void WriteModule(const Module *M, BitstreamWriter &Stream) { Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); - + // Emit the version number if it is non-zero. if (CurVersion) { SmallVector Vals; Vals.push_back(CurVersion); Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); } - + // Analyze the module, enumerating globals, functions, etc. ValueEnumerator VE(M); // Emit blockinfo, which defines the standard abbreviations etc. WriteBlockInfo(VE, Stream); - + // Emit information about parameter attributes. WriteAttributeTable(VE, Stream); - + // Emit information describing all of the types in the module. WriteTypeTable(VE, Stream); - + // Emit top-level description of module, including target triple, inline asm, // descriptors for global variables, and function prototype info. WriteModuleInfo(M, VE, Stream); @@ -1462,13 +1462,13 @@ static void WriteModule(const Module *M, BitstreamWriter &Stream) { // Emit metadata. WriteModuleMetadataStore(M, VE, Stream); - + // Emit the type symbol table information. WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream); - + // Emit names for globals/functions etc. WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); - + Stream.ExitBlock(); } @@ -1476,7 +1476,7 @@ static void WriteModule(const Module *M, BitstreamWriter &Stream) { /// header and trailer to make it compatible with the system archiver. To do /// this we emit the following header, and then emit a trailer that pads the /// file out to be a multiple of 16 bytes. -/// +/// /// struct bc_header { /// uint32_t Magic; // 0x0B17C0DE /// uint32_t Version; // Version, currently always 0. @@ -1493,7 +1493,7 @@ enum { static void EmitDarwinBCHeader(BitstreamWriter &Stream, const std::string &TT) { unsigned CPUType = ~0U; - + // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a // magic number from /usr/include/mach/machine.h. It is ok to reproduce the // specific constants here because they are implicitly part of the Darwin ABI. @@ -1502,7 +1502,7 @@ static void EmitDarwinBCHeader(BitstreamWriter &Stream, DARWIN_CPU_TYPE_X86 = 7, DARWIN_CPU_TYPE_POWERPC = 18 }; - + if (TT.find("x86_64-") == 0) CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' && @@ -1512,10 +1512,10 @@ static void EmitDarwinBCHeader(BitstreamWriter &Stream, CPUType = DARWIN_CPU_TYPE_POWERPC; else if (TT.find("powerpc64-") == 0) CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; - + // Traditional Bitcode starts after header. unsigned BCOffset = DarwinBCHeaderSize; - + Stream.Emit(0x0B17C0DE, 32); Stream.Emit(0 , 32); // Version. Stream.Emit(BCOffset , 32); @@ -1528,7 +1528,7 @@ static void EmitDarwinBCHeader(BitstreamWriter &Stream, static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) { // Update the size field in the header. Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize); - + // If the file is not a multiple of 16 bytes, insert dummy padding. while (BufferSize & 15) { Stream.Emit(0, 8); @@ -1542,18 +1542,18 @@ static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) { void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) { std::vector Buffer; BitstreamWriter Stream(Buffer); - + Buffer.reserve(256*1024); WriteBitcodeToStream( M, Stream ); - + // If writing to stdout, set binary mode. if (&llvm::outs() == &Out) sys::Program::ChangeStdoutToBinary(); // Write the generated bitstream to "Out". Out.write((char*)&Buffer.front(), Buffer.size()); - + // Make sure it hits disk now. Out.flush(); } @@ -1565,7 +1565,7 @@ void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) { bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos; if (isDarwin) EmitDarwinBCHeader(Stream, M->getTargetTriple()); - + // Emit the file header. Stream.Emit((unsigned)'B', 8); Stream.Emit((unsigned)'C', 8); diff --git a/lib/Bitcode/Writer/ValueEnumerator.cpp b/lib/Bitcode/Writer/ValueEnumerator.cpp index f4682a2f637..97219afa46e 100644 --- a/lib/Bitcode/Writer/ValueEnumerator.cpp +++ b/lib/Bitcode/Writer/ValueEnumerator.cpp @@ -57,10 +57,10 @@ ValueEnumerator::ValueEnumerator(const Module *M) { for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); I != E; ++I) EnumerateValue(I); - + // Remember what is the cutoff between globalvalue's and other constants. unsigned FirstConstant = Values.size(); - + // Enumerate the global variable initializers. for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) @@ -71,25 +71,25 @@ ValueEnumerator::ValueEnumerator(const Module *M) { for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); I != E; ++I) EnumerateValue(I->getAliasee()); - + // Enumerate types used by the type symbol table. EnumerateTypeSymbolTable(M->getTypeSymbolTable()); // Insert constants that are named at module level into the slot pool so that // the module symbol table can refer to them... EnumerateValueSymbolTable(M->getValueSymbolTable()); - + // Enumerate types used by function bodies and argument lists. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { - + for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) EnumerateType(I->getType()); - Metadata &TheMetadata = F->getContext().getMetadata(); + Metadata &TheMetadata = F->getContext().getMetadata(); for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){ - for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); + for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) EnumerateOperandType(*OI); EnumerateType(I->getType()); @@ -98,23 +98,23 @@ ValueEnumerator::ValueEnumerator(const Module *M) { else if (const InvokeInst *II = dyn_cast(I)) EnumerateAttributes(II->getAttributes()); - // Enumerate metadata attached with this instruction. - const Metadata::MDMapTy *MDs = TheMetadata.getMDs(I); - if (MDs) - for (Metadata::MDMapTy::const_iterator MI = MDs->begin(), - ME = MDs->end(); MI != ME; ++MI) - if (MDNode *MDN = dyn_cast_or_null(MI->second)) - EnumerateMetadata(MDN); + // Enumerate metadata attached with this instruction. + const Metadata::MDMapTy *MDs = TheMetadata.getMDs(I); + if (MDs) + for (Metadata::MDMapTy::const_iterator MI = MDs->begin(), + ME = MDs->end(); MI != ME; ++MI) + if (MDNode *MDN = dyn_cast_or_null(MI->second)) + EnumerateMetadata(MDN); } } - + // Optimize constant ordering. OptimizeConstants(FirstConstant, Values.size()); - + // Sort the type table by frequency so that most commonly used types are early // in the table (have low bit-width). std::stable_sort(Types.begin(), Types.end(), CompareByFrequency); - + // Partition the Type ID's so that the single-value types occur before the // aggregate types. This allows the aggregate types to be dropped from the // type table after parsing the global variable initializers. @@ -129,7 +129,7 @@ unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const { InstructionMapType::const_iterator I = InstructionMap.find(Inst); assert (I != InstructionMap.end() && "Instruction is not mapped!"); return I->second; -} +} void ValueEnumerator::setInstructionID(const Instruction *I) { InstructionMap[I] = InstructionCount++; @@ -141,12 +141,12 @@ unsigned ValueEnumerator::getValueID(const Value *V) const { assert(I != MDValueMap.end() && "Value not in slotcalculator!"); return I->second-1; } - + ValueMapType::const_iterator I = ValueMap.find(V); assert(I != ValueMap.end() && "Value not in slotcalculator!"); return I->second-1; } - + // Optimize constant ordering. namespace { struct CstSortPredicate { @@ -156,7 +156,7 @@ namespace { const std::pair &RHS) { // Sort by plane. if (LHS.first->getType() != RHS.first->getType()) - return VE.getTypeID(LHS.first->getType()) < + return VE.getTypeID(LHS.first->getType()) < VE.getTypeID(RHS.first->getType()); // Then by frequency. return LHS.second > RHS.second; @@ -167,15 +167,15 @@ namespace { /// OptimizeConstants - Reorder constant pool for denser encoding. void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) { if (CstStart == CstEnd || CstStart+1 == CstEnd) return; - + CstSortPredicate P(*this); std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P); - + // Ensure that integer constants are at the start of the constant pool. This // is important so that GEP structure indices come before gep constant exprs. std::partition(Values.begin()+CstStart, Values.begin()+CstEnd, isIntegerValue); - + // Rebuild the modified portion of ValueMap. for (; CstStart != CstEnd; ++CstStart) ValueMap[Values[CstStart].first] = CstStart+1; @@ -185,7 +185,7 @@ void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) { /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol /// table. void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) { - for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); + for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); TI != TE; ++TI) EnumerateType(TI->second); } @@ -193,7 +193,7 @@ void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) { /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol /// table into the values table. void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) { - for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); + for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); VI != VE; ++VI) EnumerateValue(VI->getValue()); } @@ -254,7 +254,7 @@ void ValueEnumerator::EnumerateValue(const Value *V) { // Enumerate the type of this value. EnumerateType(V->getType()); - + if (const Constant *C = dyn_cast(V)) { if (isa(C)) { // Initializers for globals are handled explicitly elsewhere. @@ -266,7 +266,7 @@ void ValueEnumerator::EnumerateValue(const Value *V) { // If a constant has operands, enumerate them. This makes sure that if a // constant has uses (for example an array of const ints), that they are // inserted also. - + // We prefer to enumerate them with values before we enumerate the user // itself. This makes it more likely that we can avoid forward references // in the reader. We know that there can be no cycles in the constants @@ -274,7 +274,7 @@ void ValueEnumerator::EnumerateValue(const Value *V) { for (User::const_op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) EnumerateValue(*I); - + // Finally, add the value. Doing this could make the ValueID reference be // dangling, don't reuse it. Values.push_back(std::make_pair(V, 1U)); @@ -291,17 +291,17 @@ void ValueEnumerator::EnumerateValue(const Value *V) { void ValueEnumerator::EnumerateType(const Type *Ty) { unsigned &TypeID = TypeMap[Ty]; - + if (TypeID) { // If we've already seen this type, just increase its occurrence count. Types[TypeID-1].second++; return; } - + // First time we saw this type, add it. Types.push_back(std::make_pair(Ty, 1U)); TypeID = Types.size(); - + // Enumerate subtypes. for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); I != E; ++I) @@ -347,18 +347,18 @@ void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) { void ValueEnumerator::incorporateFunction(const Function &F) { NumModuleValues = Values.size(); - + // Adding function arguments to the value table. for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) EnumerateValue(I); FirstFuncConstantID = Values.size(); - + // Add all function-level constants to the value table. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) - for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); + for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) { if ((isa(*OI) && !isa(*OI)) || isa(*OI)) @@ -367,16 +367,16 @@ void ValueEnumerator::incorporateFunction(const Function &F) { BasicBlocks.push_back(BB); ValueMap[BB] = BasicBlocks.size(); } - + // Optimize the constant layout. OptimizeConstants(FirstFuncConstantID, Values.size()); - + // Add the function's parameter attributes so they are available for use in // the function's instruction. EnumerateAttributes(F.getAttributes()); FirstInstID = Values.size(); - + // Add all of the instructions. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) { @@ -392,8 +392,7 @@ void ValueEnumerator::purgeFunction() { ValueMap.erase(Values[i].first); for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i) ValueMap.erase(BasicBlocks[i]); - + Values.resize(NumModuleValues); BasicBlocks.clear(); } - diff --git a/lib/CodeGen/DwarfEHPrepare.cpp b/lib/CodeGen/DwarfEHPrepare.cpp index 8dc7e86fd21..0ae7b35cc34 100644 --- a/lib/CodeGen/DwarfEHPrepare.cpp +++ b/lib/CodeGen/DwarfEHPrepare.cpp @@ -134,7 +134,7 @@ bool DwarfEHPrepare::NormalizeLandingPads() { break; } } - + if (OnlyUnwoundTo) { // Only unwind edges lead to the landing pad. Remember the landing pad. LandingPads.insert(LPad); @@ -254,7 +254,7 @@ bool DwarfEHPrepare::LowerUnwinds() { // Create the call... CallInst *CI = CallInst::Create(RewindFunction, - CreateReadOfExceptionValue(TI->getParent()), + CreateReadOfExceptionValue(TI->getParent()), "", TI); CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME)); // ...followed by an UnreachableInst. diff --git a/lib/CodeGen/RegAllocPBQP.cpp b/lib/CodeGen/RegAllocPBQP.cpp index b62d4def7e4..33d82d0cefb 100644 --- a/lib/CodeGen/RegAllocPBQP.cpp +++ b/lib/CodeGen/RegAllocPBQP.cpp @@ -74,7 +74,7 @@ namespace { public: static char ID; - + /// Construct a PBQP register allocator. PBQPRegAlloc() : MachineFunctionPass(&ID) {} @@ -696,7 +696,7 @@ bool PBQPRegAlloc::mapPBQPToRegAlloc(const PBQP::Solution &solution) { // Clear the existing allocation. vrm->clearAllVirt(); - + // Iterate over the nodes mapping the PBQP solution to a register assignment. for (unsigned node = 0; node < node2LI.size(); ++node) { unsigned virtReg = node2LI[node]->reg, @@ -764,7 +764,7 @@ void PBQPRegAlloc::finalizeAlloc() const { // First allocate registers for the empty intervals. for (LiveIntervalSet::const_iterator - itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end(); + itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end(); itr != end; ++itr) { LiveInterval *li = *itr; diff --git a/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp b/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp index be047403170..197b3b6b7c7 100644 --- a/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp +++ b/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp @@ -162,7 +162,7 @@ MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, "TargetLowering::EmitInstrWithCustomInserter!"; #endif llvm_unreachable(0); - return 0; + return 0; } /// EmitLiveInCopy - Emit a copy for a live in physical register. If the @@ -225,7 +225,7 @@ static void EmitLiveInCopy(MachineBasicBlock *MBB, bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC); assert(Emitted && "Unable to issue a live-in copy instruction!\n"); (void) Emitted; - + CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg)); if (Coalesced) { if (&*InsertPos == UseMI) ++InsertPos; @@ -379,13 +379,13 @@ void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, // as a tail call, cease emitting nodes for this block. for (BasicBlock::iterator I = Begin; I != End && !SDL->HasTailCall; ++I) { if (MDDbgKind) { - // Update DebugLoc if debug information is attached with this + // Update DebugLoc if debug information is attached with this // instruction. - if (MDNode *Dbg = - dyn_cast_or_null(TheMetadata.getMD(MDDbgKind, I))) { - DILocation DILoc(Dbg); - DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo()); - SDL->setCurDebugLoc(Loc); + if (MDNode *Dbg = + dyn_cast_or_null(TheMetadata.getMD(MDDbgKind, I))) { + DILocation DILoc(Dbg); + DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo()); + SDL->setCurDebugLoc(Loc); } } if (!isa(I)) @@ -407,7 +407,7 @@ void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, SDL->visit(*LLVMBB->getTerminator()); } } - + // Make sure the root of the DAG is up-to-date. CurDAG->setRoot(SDL->getControlRoot()); @@ -419,44 +419,44 @@ void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, void SelectionDAGISel::ComputeLiveOutVRegInfo() { SmallPtrSet VisitedNodes; SmallVector Worklist; - + Worklist.push_back(CurDAG->getRoot().getNode()); - + APInt Mask; APInt KnownZero; APInt KnownOne; - + while (!Worklist.empty()) { SDNode *N = Worklist.back(); Worklist.pop_back(); - + // If we've already seen this node, ignore it. if (!VisitedNodes.insert(N)) continue; - + // Otherwise, add all chain operands to the worklist. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) if (N->getOperand(i).getValueType() == MVT::Other) Worklist.push_back(N->getOperand(i).getNode()); - + // If this is a CopyToReg with a vreg dest, process it. if (N->getOpcode() != ISD::CopyToReg) continue; - + unsigned DestReg = cast(N->getOperand(1))->getReg(); if (!TargetRegisterInfo::isVirtualRegister(DestReg)) continue; - + // Ignore non-scalar or non-integer values. SDValue Src = N->getOperand(2); EVT SrcVT = Src.getValueType(); if (!SrcVT.isInteger() || SrcVT.isVector()) continue; - + unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src); Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits()); CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne); - + // Only install this information if it tells us something. if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) { DestReg -= TargetRegisterInfo::FirstVirtualRegister; @@ -494,10 +494,10 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { } else { CurDAG->Combine(Unrestricted, *AA, OptLevel); } - + DEBUG(errs() << "Optimized lowered selection DAG:\n"); DEBUG(CurDAG->dump()); - + // Second step, hack on the DAG until it only uses operations and types that // the target supports. if (!DisableLegalizeTypes) { @@ -561,7 +561,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { DEBUG(CurDAG->dump()); } } - + if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName); if (TimePassesIsEnabled) { @@ -570,10 +570,10 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { } else { CurDAG->Legalize(DisableLegalizeTypes, OptLevel); } - + DEBUG(errs() << "Legalized selection DAG:\n"); DEBUG(CurDAG->dump()); - + if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName); // Run the DAG combiner in post-legalize mode. @@ -583,12 +583,12 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { } else { CurDAG->Combine(NoIllegalOperations, *AA, OptLevel); } - + DEBUG(errs() << "Optimized legalized selection DAG:\n"); DEBUG(CurDAG->dump()); if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName); - + if (OptLevel != CodeGenOpt::None) ComputeLiveOutVRegInfo(); @@ -617,7 +617,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { if (ViewSUnitDAGs) Scheduler->viewGraph(); - // Emit machine code to BB. This can change 'BB' to the last block being + // Emit machine code to BB. This can change 'BB' to the last block being // inserted into. if (TimePassesIsEnabled) { NamedRegionTimer T("Instruction Creation", GroupName); @@ -636,7 +636,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { DEBUG(errs() << "Selected machine code:\n"); DEBUG(BB->dump()); -} +} void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF, @@ -740,17 +740,17 @@ void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, FastIS->startNewBlock(BB); // Do FastISel on as many instructions as possible. for (; BI != End; ++BI) { - if (MDDbgKind) { - // Update DebugLoc if debug information is attached with this - // instruction. - if (MDNode *Dbg = - dyn_cast_or_null(TheMetadata.getMD(MDDbgKind, BI))) { - DILocation DILoc(Dbg); - DebugLoc Loc = ExtractDebugLocation(DILoc, - MF.getDebugLocInfo()); - FastIS->setCurDebugLoc(Loc); - } - } + if (MDDbgKind) { + // Update DebugLoc if debug information is attached with this + // instruction. + if (MDNode *Dbg = + dyn_cast_or_null(TheMetadata.getMD(MDDbgKind, BI))) { + DILocation DILoc(Dbg); + DebugLoc Loc = ExtractDebugLocation(DILoc, + MF.getDebugLocInfo()); + FastIS->setCurDebugLoc(Loc); + } + } // Just before the terminator instruction, insert instructions to // feed PHI nodes in successor blocks. @@ -760,7 +760,7 @@ void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, errs() << "FastISel miss: "; BI->dump(); } - assert(!EnableFastISelAbort && + assert(!EnableFastISelAbort && "FastISel didn't handle a PHI in a successor"); break; } @@ -838,7 +838,7 @@ SelectionDAGISel::FinishBasicBlock() { errs() << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first << ", " << SDL->PHINodesToUpdate[i].second << ")\n"); - + // Next, now that we know what the last MBB the LLVM BB expanded is, update // PHI nodes in successors. if (SDL->SwitchCases.empty() && @@ -867,7 +867,7 @@ SelectionDAGISel::FinishBasicBlock() { CurDAG->setRoot(SDL->getRoot()); CodeGenAndEmitDAG(); SDL->clear(); - } + } for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) { // Set the current basic block to the mbb we wish to insert the code into @@ -882,8 +882,8 @@ SelectionDAGISel::FinishBasicBlock() { SDL->visitBitTestCase(SDL->BitTestCases[i].Default, SDL->BitTestCases[i].Reg, SDL->BitTestCases[i].Cases[j]); - - + + CurDAG->setRoot(SDL->getRoot()); CodeGenAndEmitDAG(); SDL->clear(); @@ -936,7 +936,7 @@ SelectionDAGISel::FinishBasicBlock() { CodeGenAndEmitDAG(); SDL->clear(); } - + // Set the current basic block to the mbb we wish to insert the code into BB = SDL->JTCases[i].second.MBB; SDL->setCurrentBasicBlock(BB); @@ -945,7 +945,7 @@ SelectionDAGISel::FinishBasicBlock() { CurDAG->setRoot(SDL->getRoot()); CodeGenAndEmitDAG(); SDL->clear(); - + // Update PHI Nodes for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) { MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first; @@ -968,7 +968,7 @@ SelectionDAGISel::FinishBasicBlock() { } } SDL->JTCases.clear(); - + // If the switch block involved a branch to one of the actual successors, we // need to update PHI nodes in that block. for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) { @@ -981,19 +981,19 @@ SelectionDAGISel::FinishBasicBlock() { PHI->addOperand(MachineOperand::CreateMBB(BB)); } } - + // If we generated any switch lowering information, build and codegen any // additional DAGs necessary. for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) { // Set the current basic block to the mbb we wish to insert the code into MachineBasicBlock *ThisBB = BB = SDL->SwitchCases[i].ThisBB; SDL->setCurrentBasicBlock(BB); - + // Emit the code SDL->visitSwitchCase(SDL->SwitchCases[i]); CurDAG->setRoot(SDL->getRoot()); CodeGenAndEmitDAG(); - + // Handle any PHI nodes in successors of this chunk, as if we were coming // from the original BB before switch expansion. Note that PHI nodes can // occur multiple times in PHINodesToUpdate. We have to be very careful to @@ -1020,11 +1020,11 @@ SelectionDAGISel::FinishBasicBlock() { } } } - + // Don't process RHS if same block as LHS. if (BB == SDL->SwitchCases[i].FalseBB) SDL->SwitchCases[i].FalseBB = 0; - + // If we haven't handled the RHS, do so now. Otherwise, we're done. SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB; SDL->SwitchCases[i].FalseBB = 0; @@ -1044,12 +1044,12 @@ SelectionDAGISel::FinishBasicBlock() { /// ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault(); - + if (!Ctor) { Ctor = ISHeuristic; RegisterScheduler::setDefault(Ctor); } - + return Ctor(this, OptLevel); } @@ -1066,25 +1066,25 @@ ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() { /// the dag combiner simplified the 255, we still want to match. RHS is the /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value /// specified in the .td file (e.g. 255). -bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, +bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const { const APInt &ActualMask = RHS->getAPIntValue(); const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); - + // If the actual mask exactly matches, success! if (ActualMask == DesiredMask) return true; - + // If the actual AND mask is allowing unallowed bits, this doesn't match. if (ActualMask.intersects(~DesiredMask)) return false; - + // Otherwise, the DAG Combiner may have proven that the value coming in is // either already zero or is not demanded. Check for known zero input bits. APInt NeededMask = DesiredMask & ~ActualMask; if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) return true; - + // TODO: check to see if missing bits are just not demanded. // Otherwise, this pattern doesn't match. @@ -1095,32 +1095,32 @@ bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, /// the dag combiner simplified the 255, we still want to match. RHS is the /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value /// specified in the .td file (e.g. 255). -bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, +bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const { const APInt &ActualMask = RHS->getAPIntValue(); const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); - + // If the actual mask exactly matches, success! if (ActualMask == DesiredMask) return true; - + // If the actual AND mask is allowing unallowed bits, this doesn't match. if (ActualMask.intersects(~DesiredMask)) return false; - + // Otherwise, the DAG Combiner may have proven that the value coming in is // either already zero or is not demanded. Check for known zero input bits. APInt NeededMask = DesiredMask & ~ActualMask; - + APInt KnownZero, KnownOne; CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne); - + // If all the missing bits in the or are already known to be set, match! if ((NeededMask & KnownOne) == NeededMask) return true; - + // TODO: check to see if missing bits are just not demanded. - + // Otherwise, this pattern doesn't match. return false; } @@ -1139,7 +1139,7 @@ SelectInlineAsmMemoryOperands(std::vector &Ops) { unsigned i = 2, e = InOps.size(); if (InOps[e-1].getValueType() == MVT::Flag) --e; // Don't process a flag operand if it is here. - + while (i != e) { unsigned Flags = cast(InOps[i])->getZExtValue(); if ((Flags & 7) != 4 /*MEM*/) { @@ -1156,7 +1156,7 @@ SelectInlineAsmMemoryOperands(std::vector &Ops) { llvm_report_error("Could not match memory address. Inline asm" " failure!"); } - + // Add this to the output node. EVT IntPtrTy = TLI.getPointerTy(); Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3), @@ -1165,7 +1165,7 @@ SelectInlineAsmMemoryOperands(std::vector &Ops) { i += 2; } } - + // Add the flag input back if present. if (e != InOps.size()) Ops.push_back(InOps.back()); diff --git a/lib/CodeGen/SimpleRegisterCoalescing.cpp b/lib/CodeGen/SimpleRegisterCoalescing.cpp index e90101a9ba5..5b3b6a907f1 100644 --- a/lib/CodeGen/SimpleRegisterCoalescing.cpp +++ b/lib/CodeGen/SimpleRegisterCoalescing.cpp @@ -62,7 +62,7 @@ PhysJoinTweak("tweak-phys-join-heuristics", cl::desc("Tweak heuristics for joining phys reg with vr"), cl::init(false), cl::Hidden); -static RegisterPass +static RegisterPass X("simple-register-coalescing", "Simple Register Coalescing"); // Declare that we implement the RegisterCoalescer interface @@ -110,13 +110,13 @@ bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx); assert(BLR != IntB.end() && "Live range not found!"); VNInfo *BValNo = BLR->valno; - + // Get the location that B is defined at. Two options: either this value has - // an unknown definition point or it is defined at CopyIdx. If unknown, we + // an unknown definition point or it is defined at CopyIdx. If unknown, we // can't process it. if (!BValNo->getCopy()) return false; assert(BValNo->def == CopyIdx && "Copy doesn't define the value?"); - + // AValNo is the value number in A that defines the copy, A3 in the example. MachineInstrIndex CopyUseIdx = li_->getUseIndex(CopyIdx); LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx); @@ -142,28 +142,28 @@ bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, // The coalescer has no idea there was a def in the middle of [174,230]. if (AValNo->hasRedefByEC()) return false; - - // If AValNo is defined as a copy from IntB, we can potentially process this. + + // If AValNo is defined as a copy from IntB, we can potentially process this. // Get the instruction that defines this value number. unsigned SrcReg = li_->getVNInfoSourceReg(AValNo); if (!SrcReg) return false; // Not defined by a copy. - + // If the value number is not defined by a copy instruction, ignore it. // If the source register comes from an interval other than IntB, we can't // handle this. if (SrcReg != IntB.reg) return false; - + // Get the LiveRange in IntB that this value number starts with. LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(li_->getPrevSlot(AValNo->def)); assert(ValLR != IntB.end() && "Live range not found!"); - + // Make sure that the end of the live range is inside the same block as // CopyMI. MachineInstr *ValLREndInst = li_->getInstructionFromIndex(li_->getPrevSlot(ValLR->end)); - if (!ValLREndInst || + if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent()) return false; // Okay, we now know that ValLR ends in the same block that the CopyMI @@ -185,26 +185,26 @@ bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, return false; } } - + DEBUG({ errs() << "\nExtending: "; IntB.print(errs(), tri_); }); - + MachineInstrIndex FillerStart = ValLR->end, FillerEnd = BLR->start; // We are about to delete CopyMI, so need to remove it as the 'instruction // that defines this value #'. Update the the valnum with the new defining // instruction #. BValNo->def = FillerStart; BValNo->setCopy(0); - + // Okay, we can merge them. We need to insert a new liverange: // [ValLR.end, BLR.begin) of either value number, then we merge the // two value numbers. IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo)); // If the IntB live range is assigned to a physical register, and if that - // physreg has sub-registers, update their live intervals as well. + // physreg has sub-registers, update their live intervals as well. if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) { for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) { LiveInterval &SRLI = li_->getInterval(*SR); @@ -309,13 +309,13 @@ bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA, LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx); assert(BLR != IntB.end() && "Live range not found!"); VNInfo *BValNo = BLR->valno; - + // Get the location that B is defined at. Two options: either this value has - // an unknown definition point or it is defined at CopyIdx. If unknown, we + // an unknown definition point or it is defined at CopyIdx. If unknown, we // can't process it. if (!BValNo->getCopy()) return false; assert(BValNo->def == CopyIdx && "Copy doesn't define the value?"); - + // AValNo is the value number in A that defines the copy, A3 in the example. LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx)); @@ -491,7 +491,7 @@ bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA, IntB.addRange(LiveRange(AI->start, End, ValNo)); // If the IntB live range is assigned to a physical register, and if that - // physreg has sub-registers, update their live intervals as well. + // physreg has sub-registers, update their live intervals as well. if (BHasSubRegs) { for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) { LiveInterval &SRLI = li_->getInterval(*SR); @@ -832,11 +832,11 @@ void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg, // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814) // // bb5: - // 60 %reg1027 = t2MOVr %reg1027, 14, %reg0, %reg0 - // 68 %reg1027 = t2LDRi12 %reg1027, 8, 14, %reg0 - // 76 t2CMPzri %reg1038, 0, 14, %reg0, %CPSR - // 84 %reg1027 = t2MOVr %reg1027, 14, %reg0, %reg0 - // 96 t2Bcc mbb, 1, %CPSR + // 60 %reg1027 = t2MOVr %reg1027, 14, %reg0, %reg0 + // 68 %reg1027 = t2LDRi12 %reg1027, 8, 14, %reg0 + // 76 t2CMPzri %reg1038, 0, 14, %reg0, %CPSR + // 84 %reg1027 = t2MOVr %reg1027, 14, %reg0, %reg0 + // 96 t2Bcc mbb, 1, %CPSR // // Do not remove the kill marker on t2LDRi12. UseMO.setIsKill(false); @@ -1309,7 +1309,7 @@ bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { DEBUG(errs() << "\tCopy already coalesced.\n"); return false; // Not coalescable. } - + bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg); bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg); @@ -1318,7 +1318,7 @@ bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { DEBUG(errs() << "\tCan not coalesce physregs.\n"); return false; // Not coalescable. } - + // We only join virtual registers with allocatable physical registers. if (SrcIsPhys && !allocatableRegs_[SrcReg]) { DEBUG(errs() << "\tSrc reg is unallocatable physreg.\n"); @@ -1543,7 +1543,7 @@ bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { return false; if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg)) return false; - + LiveInterval &SrcInt = li_->getInterval(SrcReg); LiveInterval &DstInt = li_->getInterval(DstReg); assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg && @@ -1643,7 +1643,7 @@ bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { if (!isExtSubReg && !isInsSubReg && !isSubRegToReg && ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI)) return true; - + // If we can eliminate the copy without merging the live ranges, do so now. if (!isExtSubReg && !isInsSubReg && !isSubRegToReg && (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) || @@ -1651,7 +1651,7 @@ bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { JoinedCopies.insert(CopyMI); return true; } - + // Otherwise, we are unable to join the intervals. DEBUG(errs() << "Interference!\n"); Again = true; // May be possible to coalesce later. @@ -1666,7 +1666,7 @@ bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { } assert(TargetRegisterInfo::isVirtualRegister(SrcReg) && "LiveInterval::join didn't work right!"); - + // If we're about to merge live ranges into a physical register live interval, // we have to update any aliased register's live ranges to indicate that they // have clobbered values for this range. @@ -1687,7 +1687,7 @@ bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) { RealInt.addKills(NewValNo, ValNo->kills); RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo); } - RealInt.weight += SavedLI->weight; + RealInt.weight += SavedLI->weight; DstReg = RealDstReg ? RealDstReg : RealSrcReg; } @@ -1806,7 +1806,7 @@ static unsigned ComputeUltimateVN(VNInfo *VNI, // been computed, return it. if (OtherValNoAssignments[OtherValNo->id] >= 0) return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id]; - + // Mark this value number as currently being computed, then ask what the // ultimate value # of the other value is. ThisValNoAssignments[VN] = -2; @@ -1856,16 +1856,16 @@ bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li, /// joins them and returns true. bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ assert(RHS.containsOneValue()); - + // Some number (potentially more than one) value numbers in the current // interval may be defined as copies from the RHS. Scan the overlapping // portions of the LHS and RHS, keeping track of this and looking for // overlapping live ranges that are NOT defined as copies. If these exist, we // cannot coalesce. - + LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end(); LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end(); - + if (LHSIt->start < RHSIt->start) { LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start); if (LHSIt != LHS.begin()) --LHSIt; @@ -1873,9 +1873,9 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start); if (RHSIt != RHS.begin()) --RHSIt; } - + SmallVector EliminatedLHSVals; - + while (1) { // Determine if these live intervals overlap. bool Overlaps = false; @@ -1883,7 +1883,7 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ Overlaps = LHSIt->end > RHSIt->start; else Overlaps = RHSIt->end > LHSIt->start; - + // If the live intervals overlap, there are two interesting cases: if the // LHS interval is defined by a copy from the RHS, it's ok and we record // that the LHS value # is the same as the RHS. If it's not, then we cannot @@ -1901,7 +1901,7 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ // vr1025 = copy vr1024 // .. // BB2: - // vr1024 = op + // vr1024 = op // = vr1025 // Even though vr1025 is copied from vr1024, it's not safe to // coalesce them since the live range of vr1025 intersects the @@ -1910,12 +1910,12 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ return false; EliminatedLHSVals.push_back(LHSIt->valno); } - + // We know this entire LHS live range is okay, so skip it now. if (++LHSIt == LHSEnd) break; continue; } - + if (LHSIt->end < RHSIt->end) { if (++LHSIt == LHSEnd) break; } else { @@ -1939,7 +1939,7 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ // vr1025 = copy vr1024 // .. // BB2: - // vr1024 = op + // vr1024 = op // = vr1025 // Even though vr1025 is copied from vr1024, it's not safe to // coalesced them since live range of vr1025 intersects the @@ -1953,11 +1953,11 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ } } } - + if (++RHSIt == RHSEnd) break; } } - + // If we got here, we know that the coalescing will be successful and that // the value numbers in EliminatedLHSVals will all be merged together. Since // the most common case is that EliminatedLHSVals has a single number, we @@ -1989,14 +1989,14 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ } else { LHSValNo = EliminatedLHSVals[0]; } - + // Okay, now that there is a single LHS value number that we're merging the // RHS into, update the value number info for the LHS to indicate that the // value number is defined where the RHS value number was. const VNInfo *VNI = RHS.getValNumInfo(0); LHSValNo->def = VNI->def; LHSValNo->setCopy(VNI->getCopy()); - + // Okay, the final step is to loop over the RHS live intervals, adding them to // the LHS. if (VNI->hasPHIKill()) @@ -2007,7 +2007,7 @@ bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){ LHS.ComputeJoinedWeight(RHS); // Update regalloc hint if both are virtual registers. - if (TargetRegisterInfo::isVirtualRegister(LHS.reg) && + if (TargetRegisterInfo::isVirtualRegister(LHS.reg) && TargetRegisterInfo::isVirtualRegister(RHS.reg)) { std::pair RHSPref = mri_->getRegAllocationHint(RHS.reg); std::pair LHSPref = mri_->getRegAllocationHint(LHS.reg); @@ -2094,13 +2094,13 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, } } } - + // Compute ultimate value numbers for the LHS and RHS values. if (RHS.containsOneValue()) { // Copies from a liveinterval with a single value are simple to handle and // very common, handle the special case here. This is important, because // often RHS is small and LHS is large (e.g. a physreg). - + // Find out if the RHS is defined as a copy from some value in the LHS. int RHSVal0DefinedFromLHS = -1; int RHSValID = -1; @@ -2123,11 +2123,11 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, RHSValID = RHSValNoInfo->id; RHSVal0DefinedFromLHS = RHSValID; } - + LHSValNoAssignments.resize(LHS.getNumValNums(), -1); RHSValNoAssignments.resize(RHS.getNumValNums(), -1); NewVNInfo.resize(LHS.getNumValNums(), NULL); - + // Okay, *all* of the values in LHS that are defined as a copy from RHS // should now get updated. for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end(); @@ -2159,7 +2159,7 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, LHSValNoAssignments[VN] = VN; } } - + assert(RHSValID != -1 && "Didn't find value #?"); RHSValNoAssignments[0] = RHSValID; if (RHSVal0DefinedFromLHS != -1) { @@ -2175,17 +2175,17 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, VNInfo *VNI = *i; if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy? continue; - + // DstReg is known to be a register in the LHS interval. If the src is // from the RHS interval, we can use its value #. if (li_->getVNInfoSourceReg(VNI) != RHS.reg) continue; - + // Figure out the value # from the RHS. LHSValsDefinedFromRHS[VNI]= RHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno; } - + // Loop over the value numbers of the RHS, seeing if any are defined from // the LHS. for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end(); @@ -2193,26 +2193,26 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, VNInfo *VNI = *i; if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy? continue; - + // DstReg is known to be a register in the RHS interval. If the src is // from the LHS interval, we can use its value #. if (li_->getVNInfoSourceReg(VNI) != LHS.reg) continue; - + // Figure out the value # from the LHS. RHSValsDefinedFromLHS[VNI]= LHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno; } - + LHSValNoAssignments.resize(LHS.getNumValNums(), -1); RHSValNoAssignments.resize(RHS.getNumValNums(), -1); NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums()); - + for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end(); i != e; ++i) { VNInfo *VNI = *i; unsigned VN = VNI->id; - if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused()) + if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused()) continue; ComputeUltimateVN(VNI, NewVNInfo, LHSValsDefinedFromRHS, RHSValsDefinedFromLHS, @@ -2230,20 +2230,20 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, RHSValNoAssignments[VN] = NewVNInfo.size()-1; continue; } - + ComputeUltimateVN(VNI, NewVNInfo, RHSValsDefinedFromLHS, LHSValsDefinedFromRHS, RHSValNoAssignments, LHSValNoAssignments); } } - + // Armed with the mappings of LHS/RHS values to ultimate values, walk the // interval lists to see if these intervals are coalescable. LiveInterval::const_iterator I = LHS.begin(); LiveInterval::const_iterator IE = LHS.end(); LiveInterval::const_iterator J = RHS.begin(); LiveInterval::const_iterator JE = RHS.end(); - + // Skip ahead until the first place of potential sharing. if (I->start < J->start) { I = std::upper_bound(I, IE, J->start); @@ -2252,7 +2252,7 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, J = std::upper_bound(J, JE, I->start); if (J != RHS.begin()) --J; } - + while (1) { // Determine if these two live ranges overlap. bool Overlaps; @@ -2270,7 +2270,7 @@ SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS, RHSValNoAssignments[J->valno->id]) return false; } - + if (I->end < J->end) { ++I; if (I == IE) break; @@ -2341,7 +2341,7 @@ void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB, for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end(); MII != E;) { MachineInstr *Inst = MII++; - + // If this isn't a copy nor a extract_subreg, we can't join intervals. unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) { @@ -2419,7 +2419,7 @@ void SimpleRegisterCoalescing::joinIntervals() { for (unsigned i = 0, e = MBBs.size(); i != e; ++i) CopyCoalesceInMBB(MBBs[i].second, TryAgainList); } - + // Joining intervals can allow other intervals to be joined. Iteratively join // until we make no progress. bool ProgressMade = true; @@ -2706,7 +2706,7 @@ bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) { if (Hint.first || Hint.second) LI.weight *= 1.01F; - // Divide the weight of the interval by its size. This encourages + // Divide the weight of the interval by its size. This encourages // spilling of intervals that are large and have few uses, and // discourages spilling of small intervals with many uses. LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM; diff --git a/lib/Support/APInt.cpp b/lib/Support/APInt.cpp index d7706268dc2..56d47736eab 100644 --- a/lib/Support/APInt.cpp +++ b/lib/Support/APInt.cpp @@ -2054,7 +2054,7 @@ void APInt::fromString(unsigned numbits, const StringRef& str, uint8_t radix) { assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width"); assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width"); assert((((slen-1)*64)/22 <= numbits || radix != 10) - && "Insufficient bit width"); + && "Insufficient bit width"); // Allocate memory if (!isSingleWord()) diff --git a/lib/Target/Alpha/AlphaCodeEmitter.cpp b/lib/Target/Alpha/AlphaCodeEmitter.cpp index 735708c34b0..f7089ad79c3 100644 --- a/lib/Target/Alpha/AlphaCodeEmitter.cpp +++ b/lib/Target/Alpha/AlphaCodeEmitter.cpp @@ -31,7 +31,7 @@ using namespace llvm; namespace { - + class AlphaCodeEmitter { MachineCodeEmitter &MCE; public: @@ -60,7 +60,7 @@ namespace { public: static char ID; explicit Emitter(TargetMachine &tm, CodeEmitter &mce) - : MachineFunctionPass(&ID), AlphaCodeEmitter(mce), + : MachineFunctionPass(&ID), AlphaCodeEmitter(mce), II(0), TM(tm), MCE(mce) {} Emitter(TargetMachine &tm, CodeEmitter &mce, const AlphaInstrInfo& ii) : MachineFunctionPass(&ID), AlphaCodeEmitter(mce), diff --git a/lib/Target/Alpha/AlphaISelLowering.cpp b/lib/Target/Alpha/AlphaISelLowering.cpp index 777ab524ada..b3f865cf4a8 100644 --- a/lib/Target/Alpha/AlphaISelLowering.cpp +++ b/lib/Target/Alpha/AlphaISelLowering.cpp @@ -48,9 +48,9 @@ AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM) //I am having problems with shr n i8 1 setShiftAmountType(MVT::i64); setBooleanContents(ZeroOrOneBooleanContent); - + setUsesGlobalOffsetTable(true); - + addRegisterClass(MVT::i64, Alpha::GPRCRegisterClass); addRegisterClass(MVT::f64, Alpha::F8RCRegisterClass); addRegisterClass(MVT::f32, Alpha::F4RCRegisterClass); @@ -60,10 +60,10 @@ AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM) setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote); setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand); - + setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote); setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand); - + setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand); setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand); @@ -73,13 +73,13 @@ AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM) // setOperationAction(ISD::BRIND, MVT::Other, Expand); setOperationAction(ISD::BR_JT, MVT::Other, Expand); setOperationAction(ISD::BR_CC, MVT::Other, Expand); - setOperationAction(ISD::SELECT_CC, MVT::Other, Expand); + setOperationAction(ISD::SELECT_CC, MVT::Other, Expand); setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); setOperationAction(ISD::FREM, MVT::f32, Expand); setOperationAction(ISD::FREM, MVT::f64, Expand); - + setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); @@ -93,7 +93,7 @@ AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM) setOperationAction(ISD::BSWAP , MVT::i64, Expand); setOperationAction(ISD::ROTL , MVT::i64, Expand); setOperationAction(ISD::ROTR , MVT::i64, Expand); - + setOperationAction(ISD::SREM , MVT::i64, Custom); setOperationAction(ISD::UREM , MVT::i64, Custom); setOperationAction(ISD::SDIV , MVT::i64, Custom); @@ -134,7 +134,7 @@ AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM) setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); // Not implemented yet. - setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); + setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); @@ -202,7 +202,7 @@ static SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) { SDValue Zero = DAG.getConstant(0, PtrVT); // FIXME there isn't really any debug info here DebugLoc dl = Op.getDebugLoc(); - + SDValue Hi = DAG.getNode(AlphaISD::GPRelHi, dl, MVT::i64, JTI, DAG.getGLOBAL_OFFSET_TABLE(MVT::i64)); SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, JTI, Hi); @@ -403,7 +403,7 @@ AlphaTargetLowering::LowerFormalArguments(SDValue Chain, Alpha::R16, Alpha::R17, Alpha::R18, Alpha::R19, Alpha::R20, Alpha::R21}; unsigned args_float[] = { Alpha::F16, Alpha::F17, Alpha::F18, Alpha::F19, Alpha::F20, Alpha::F21}; - + for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { SDValue argt; EVT ObjectVT = Ins[ArgNo].VT; @@ -414,17 +414,17 @@ AlphaTargetLowering::LowerFormalArguments(SDValue Chain, default: assert(false && "Invalid value type!"); case MVT::f64: - args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], + args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], &Alpha::F8RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT); break; case MVT::f32: - args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], + args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], &Alpha::F4RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT); break; case MVT::i64: - args_int[ArgNo] = AddLiveIn(MF, args_int[ArgNo], + args_int[ArgNo] = AddLiveIn(MF, args_int[ArgNo], &Alpha::GPRCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, args_int[ArgNo], MVT::i64); break; @@ -495,7 +495,7 @@ AlphaTargetLowering::LowerReturn(SDValue Chain, assert(ArgVT.isFloatingPoint()); ArgReg = Alpha::F0; } - Copy = DAG.getCopyToReg(Copy, dl, ArgReg, + Copy = DAG.getCopyToReg(Copy, dl, ArgReg, Outs[0].Val, Copy.getValue(1)); if (DAG.getMachineFunction().getRegInfo().liveout_empty()) DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg); @@ -512,22 +512,22 @@ AlphaTargetLowering::LowerReturn(SDValue Chain, ArgReg1 = Alpha::F0; ArgReg2 = Alpha::F1; } - Copy = DAG.getCopyToReg(Copy, dl, ArgReg1, + Copy = DAG.getCopyToReg(Copy, dl, ArgReg1, Outs[0].Val, Copy.getValue(1)); - if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), + if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg1) == DAG.getMachineFunction().getRegInfo().liveout_end()) DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg1); - Copy = DAG.getCopyToReg(Copy, dl, ArgReg2, + Copy = DAG.getCopyToReg(Copy, dl, ArgReg2, Outs[1].Val, Copy.getValue(1)); - if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), + if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg2) == DAG.getMachineFunction().getRegInfo().liveout_end()) DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg2); break; } } - return DAG.getNode(AlphaISD::RET_FLAG, dl, + return DAG.getNode(AlphaISD::RET_FLAG, dl, MVT::Other, Copy, Copy.getValue(1)); } @@ -573,7 +573,7 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { switch (IntNo) { default: break; // Don't custom lower most intrinsics. case Intrinsic::alpha_umulh: - return DAG.getNode(ISD::MULHU, dl, MVT::i64, + return DAG.getNode(ISD::MULHU, dl, MVT::i64, Op.getOperand(1), Op.getOperand(2)); } } @@ -582,14 +582,14 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { SDValue ShOpLo = Op.getOperand(0); SDValue ShOpHi = Op.getOperand(1); SDValue ShAmt = Op.getOperand(2); - SDValue bm = DAG.getNode(ISD::SUB, dl, MVT::i64, - DAG.getConstant(64, MVT::i64), ShAmt); + SDValue bm = DAG.getNode(ISD::SUB, dl, MVT::i64, + DAG.getConstant(64, MVT::i64), ShAmt); SDValue BMCC = DAG.getSetCC(dl, MVT::i64, bm, DAG.getConstant(0, MVT::i64), ISD::SETLE); // if 64 - shAmt <= 0 SDValue Hi_Neg = DAG.getConstant(0, MVT::i64); SDValue ShAmt_Neg = DAG.getNode(ISD::SUB, dl, MVT::i64, - DAG.getConstant(0, MVT::i64), bm); + DAG.getConstant(0, MVT::i64), bm); SDValue Lo_Neg = DAG.getNode(ISD::SRL, dl, MVT::i64, ShOpHi, ShAmt_Neg); // else SDValue carries = DAG.getNode(ISD::SHL, dl, MVT::i64, ShOpHi, bm); @@ -601,7 +601,7 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { SDValue Lo = DAG.getNode(ISD::SELECT, dl, MVT::i64, BMCC, Lo_Neg, Lo_Pos); SDValue Ops[2] = { Lo, Hi }; return DAG.getMergeValues(Ops, 2, dl); - } + } // case ISD::SRA_PARTS: // case ISD::SHL_PARTS: @@ -623,7 +623,7 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { if (!isDouble) //Promote src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, src); - + src = DAG.getNode(AlphaISD::CVTTQ_, dl, MVT::f64, src); return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, src); @@ -633,7 +633,7 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { Constant *C = CP->getConstVal(); SDValue CPI = DAG.getTargetConstantPool(C, MVT::i64, CP->getAlignment()); // FIXME there isn't really any debug info here - + SDValue Hi = DAG.getNode(AlphaISD::GPRelHi, dl, MVT::i64, CPI, DAG.getGLOBAL_OFFSET_TABLE(MVT::i64)); SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, CPI, Hi); @@ -654,11 +654,11 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, GA, Hi); return Lo; } else - return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, GA, + return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, GA, DAG.getGLOBAL_OFFSET_TABLE(MVT::i64)); } case ISD::ExternalSymbol: { - return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, + return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, DAG.getTargetExternalSymbol(cast(Op) ->getSymbol(), MVT::i64), DAG.getGLOBAL_OFFSET_TABLE(MVT::i64)); @@ -681,7 +681,7 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { case ISD::UDIV: if (Op.getValueType().isInteger()) { if (Op.getOperand(1).getOpcode() == ISD::Constant) - return Op.getOpcode() == ISD::SDIV ? BuildSDIV(Op.getNode(), DAG, NULL) + return Op.getOpcode() == ISD::SDIV ? BuildSDIV(Op.getNode(), DAG, NULL) : BuildUDIV(Op.getNode(), DAG, NULL); const char* opstr = 0; switch (Op.getOpcode()) { @@ -715,12 +715,12 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { SDValue SrcP = Op.getOperand(2); const Value *DestS = cast(Op.getOperand(3))->getValue(); const Value *SrcS = cast(Op.getOperand(4))->getValue(); - + SDValue Val = DAG.getLoad(getPointerTy(), dl, Chain, SrcP, SrcS, 0); SDValue Result = DAG.getStore(Val.getValue(1), dl, Val, DestP, DestS, 0); - SDValue NP = DAG.getNode(ISD::ADD, dl, MVT::i64, SrcP, + SDValue NP = DAG.getNode(ISD::ADD, dl, MVT::i64, SrcP, DAG.getConstant(8, MVT::i64)); - Val = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Result, + Val = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Result, NP, NULL,0, MVT::i32); SDValue NPD = DAG.getNode(ISD::ADD, dl, MVT::i64, DestP, DAG.getConstant(8, MVT::i64)); @@ -730,7 +730,7 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { SDValue Chain = Op.getOperand(0); SDValue VAListP = Op.getOperand(1); const Value *VAListS = cast(Op.getOperand(2))->getValue(); - + // vastart stores the address of the VarArgsBase and VarArgsOffset SDValue FR = DAG.getFrameIndex(VarArgsBase, MVT::i64); SDValue S1 = DAG.getStore(Chain, dl, FR, VAListP, VAListS, 0); @@ -739,13 +739,13 @@ SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { return DAG.getTruncStore(S1, dl, DAG.getConstant(VarArgsOffset, MVT::i64), SA2, NULL, 0, MVT::i32); } - case ISD::RETURNADDR: + case ISD::RETURNADDR: return DAG.getNode(AlphaISD::GlobalRetAddr, DebugLoc::getUnknownLoc(), MVT::i64); //FIXME: implement case ISD::FRAMEADDR: break; } - + return SDValue(); } @@ -769,7 +769,7 @@ void AlphaTargetLowering::ReplaceNodeResults(SDNode *N, /// getConstraintType - Given a constraint letter, return the type of /// constraint it is for this target. -AlphaTargetLowering::ConstraintType +AlphaTargetLowering::ConstraintType AlphaTargetLowering::getConstraintType(const std::string &Constraint) const { if (Constraint.size() == 1) { switch (Constraint[0]) { @@ -788,33 +788,33 @@ getRegClassForInlineAsmConstraint(const std::string &Constraint, if (Constraint.size() == 1) { switch (Constraint[0]) { default: break; // Unknown constriant letter - case 'f': + case 'f': return make_vector(Alpha::F0 , Alpha::F1 , Alpha::F2 , Alpha::F3 , Alpha::F4 , Alpha::F5 , - Alpha::F6 , Alpha::F7 , Alpha::F8 , - Alpha::F9 , Alpha::F10, Alpha::F11, - Alpha::F12, Alpha::F13, Alpha::F14, - Alpha::F15, Alpha::F16, Alpha::F17, - Alpha::F18, Alpha::F19, Alpha::F20, - Alpha::F21, Alpha::F22, Alpha::F23, - Alpha::F24, Alpha::F25, Alpha::F26, - Alpha::F27, Alpha::F28, Alpha::F29, + Alpha::F6 , Alpha::F7 , Alpha::F8 , + Alpha::F9 , Alpha::F10, Alpha::F11, + Alpha::F12, Alpha::F13, Alpha::F14, + Alpha::F15, Alpha::F16, Alpha::F17, + Alpha::F18, Alpha::F19, Alpha::F20, + Alpha::F21, Alpha::F22, Alpha::F23, + Alpha::F24, Alpha::F25, Alpha::F26, + Alpha::F27, Alpha::F28, Alpha::F29, Alpha::F30, Alpha::F31, 0); - case 'r': - return make_vector(Alpha::R0 , Alpha::R1 , Alpha::R2 , - Alpha::R3 , Alpha::R4 , Alpha::R5 , - Alpha::R6 , Alpha::R7 , Alpha::R8 , - Alpha::R9 , Alpha::R10, Alpha::R11, - Alpha::R12, Alpha::R13, Alpha::R14, - Alpha::R15, Alpha::R16, Alpha::R17, - Alpha::R18, Alpha::R19, Alpha::R20, - Alpha::R21, Alpha::R22, Alpha::R23, - Alpha::R24, Alpha::R25, Alpha::R26, - Alpha::R27, Alpha::R28, Alpha::R29, + case 'r': + return make_vector(Alpha::R0 , Alpha::R1 , Alpha::R2 , + Alpha::R3 , Alpha::R4 , Alpha::R5 , + Alpha::R6 , Alpha::R7 , Alpha::R8 , + Alpha::R9 , Alpha::R10, Alpha::R11, + Alpha::R12, Alpha::R13, Alpha::R14, + Alpha::R15, Alpha::R16, Alpha::R17, + Alpha::R18, Alpha::R19, Alpha::R20, + Alpha::R21, Alpha::R22, Alpha::R23, + Alpha::R24, Alpha::R25, Alpha::R26, + Alpha::R27, Alpha::R28, Alpha::R29, Alpha::R30, Alpha::R31, 0); } } - + return std::vector(); } //===----------------------------------------------------------------------===// @@ -834,10 +834,10 @@ AlphaTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, MI->getOpcode() == Alpha::SWAP64) && "Unexpected instr type to insert"); - bool is32 = MI->getOpcode() == Alpha::CAS32 || + bool is32 = MI->getOpcode() == Alpha::CAS32 || MI->getOpcode() == Alpha::LAS32 || MI->getOpcode() == Alpha::SWAP32; - + //Load locked store conditional for atomic ops take on the same form //start: //ll @@ -849,14 +849,14 @@ AlphaTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, DebugLoc dl = MI->getDebugLoc(); MachineFunction::iterator It = BB; ++It; - + MachineBasicBlock *thisMBB = BB; MachineFunction *F = BB->getParent(); MachineBasicBlock *llscMBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); // Inform sdisel of the edge changes. - for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), + for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), E = BB->succ_end(); I != E; ++I) EM->insert(std::make_pair(*I, sinkMBB)); @@ -866,18 +866,18 @@ AlphaTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, F->insert(It, sinkMBB); BuildMI(thisMBB, dl, TII->get(Alpha::BR)).addMBB(llscMBB); - + unsigned reg_res = MI->getOperand(0).getReg(), reg_ptr = MI->getOperand(1).getReg(), reg_v2 = MI->getOperand(2).getReg(), reg_store = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass); - BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::LDL_L : Alpha::LDQ_L), + BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::LDL_L : Alpha::LDQ_L), reg_res).addImm(0).addReg(reg_ptr); switch (MI->getOpcode()) { case Alpha::CAS32: case Alpha::CAS64: { - unsigned reg_cmp + unsigned reg_cmp = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass); BuildMI(llscMBB, dl, TII->get(Alpha::CMPEQ), reg_cmp) .addReg(reg_v2).addReg(reg_res); diff --git a/lib/Target/Blackfin/BlackfinISelLowering.cpp b/lib/Target/Blackfin/BlackfinISelLowering.cpp index 7c36b01b167..a3d86954c32 100644 --- a/lib/Target/Blackfin/BlackfinISelLowering.cpp +++ b/lib/Target/Blackfin/BlackfinISelLowering.cpp @@ -173,7 +173,7 @@ BlackfinTargetLowering::LowerFormalArguments(SDValue Chain, SmallVector ArgLocs; CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext()); - CCInfo.AllocateStack(12, 4); // ABI requires 12 bytes stack space + CCInfo.AllocateStack(12, 4); // ABI requires 12 bytes stack space CCInfo.AnalyzeFormalArguments(Ins, CC_Blackfin); for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { @@ -286,7 +286,7 @@ BlackfinTargetLowering::LowerCall(SDValue Chain, SDValue Callee, SmallVector ArgLocs; CCState CCInfo(CallConv, isVarArg, DAG.getTarget(), ArgLocs, *DAG.getContext()); - CCInfo.AllocateStack(12, 4); // ABI requires 12 bytes stack space + CCInfo.AllocateStack(12, 4); // ABI requires 12 bytes stack space CCInfo.AnalyzeCallOperands(Outs, CC_Blackfin); // Get the size of the outgoing arguments stack space requirement. diff --git a/lib/Target/PowerPC/PPCCodeEmitter.cpp b/lib/Target/PowerPC/PPCCodeEmitter.cpp index 16535b258d9..3d62f2b8694 100644 --- a/lib/Target/PowerPC/PPCCodeEmitter.cpp +++ b/lib/Target/PowerPC/PPCCodeEmitter.cpp @@ -90,7 +90,7 @@ namespace { template char Emitter::ID = 0; } - + /// createPPCCodeEmitterPass - Return a pass that emits the collected PPC code /// to the specified MCE object. @@ -129,7 +129,7 @@ bool Emitter::runOnMachineFunction(MachineFunction &MF) { template void Emitter::emitBasicBlock(MachineBasicBlock &MBB) { MCE.StartMachineBasicBlock(&MBB); - + for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){ const MachineInstr &MI = *I; MCE.processDebugLoc(MI.getDebugLoc()); @@ -202,7 +202,7 @@ unsigned PPCCodeEmitter::getMachineOpValue(const MachineInstr &MI, case PPC::LWZ8: case PPC::LFS: case PPC::LFD: - + // Stores. case PPC::STB: case PPC::STB8: @@ -223,7 +223,7 @@ unsigned PPCCodeEmitter::getMachineOpValue(const MachineInstr &MI, break; } } - + MachineRelocation R; if (MO.isGlobal()) { R = MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc, @@ -240,7 +240,7 @@ unsigned PPCCodeEmitter::getMachineOpValue(const MachineInstr &MI, R = MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(), Reloc, MO.getIndex(), 0); } - + // If in PIC mode, we need to encode the negated address of the // 'movepctolr' into the unrelocated field. After relocation, we'll have // &gv-&movepctolr-4 in the imm field. Once &movepctolr is added to the imm @@ -251,7 +251,7 @@ unsigned PPCCodeEmitter::getMachineOpValue(const MachineInstr &MI, R.setConstantVal(-(intptr_t)MovePCtoLROffset - 4); } MCE.addRelocation(R); - + } else if (MO.isMBB()) { unsigned Reloc = 0; unsigned Opcode = MI.getOpcode(); diff --git a/lib/Target/X86/X86ISelLowering.cpp b/lib/Target/X86/X86ISelLowering.cpp index b99739d13bb..1ce51377992 100644 --- a/lib/Target/X86/X86ISelLowering.cpp +++ b/lib/Target/X86/X86ISelLowering.cpp @@ -7668,7 +7668,7 @@ X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, // all of this code can be replaced with that in the .td file. MachineBasicBlock * X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, - unsigned numArgs, bool memArg) const { + unsigned numArgs, bool memArg) const { MachineFunction *F = BB->getParent(); DebugLoc dl = MI->getDebugLoc(); @@ -7771,7 +7771,7 @@ X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, DenseMap *EM) const { const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); DebugLoc DL = MI->getDebugLoc(); - + // To "insert" a SELECT_CC instruction, we actually have to insert the // diamond control-flow pattern. The incoming instruction knows the // destination vreg to set, the condition code register to branch on, the @@ -7779,7 +7779,7 @@ X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, const BasicBlock *LLVM_BB = BB->getBasicBlock(); MachineFunction::iterator It = BB; ++It; - + // thisMBB: // ... // TrueVal = ... @@ -7798,7 +7798,7 @@ X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, // Update machine-CFG edges by first adding all successors of the current // block to the new block which will contain the Phi node for the select. // Also inform sdisel of the edge changes. - for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), + for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), E = BB->succ_end(); I != E; ++I) { EM->insert(std::make_pair(*I, sinkMBB)); sinkMBB->addSuccessor(*I); @@ -7810,15 +7810,15 @@ X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, // Add the true and fallthrough blocks as its successors. BB->addSuccessor(copy0MBB); BB->addSuccessor(sinkMBB); - + // copy0MBB: // %FalseValue = ... // # fallthrough to sinkMBB BB = copy0MBB; - + // Update machine-CFG edges BB->addSuccessor(sinkMBB); - + // sinkMBB: // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] // ... @@ -9374,12 +9374,12 @@ X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, (Constraint[4] >= '0' && Constraint[4] <= '7') && Constraint[5] == ')' && Constraint[6] == '}') { - + Res.first = X86::ST0+Constraint[4]-'0'; Res.second = X86::RFP80RegisterClass; return Res; } - + // GCC allows "st(0)" to be called just plain "st". if (StringsEqualNoCase("{st}", Constraint)) { Res.first = X86::ST0; @@ -9393,7 +9393,7 @@ X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, Res.second = X86::CCRRegisterClass; return Res; } - + // 'A' means EAX + EDX. if (Constraint == "A") { Res.first = X86::EAX; diff --git a/lib/Transforms/IPO/MergeFunctions.cpp b/lib/Transforms/IPO/MergeFunctions.cpp index 9c8592e8eb1..13bbf9c682e 100644 --- a/lib/Transforms/IPO/MergeFunctions.cpp +++ b/lib/Transforms/IPO/MergeFunctions.cpp @@ -582,19 +582,19 @@ static bool fold(std::vector &FnVec, unsigned i, unsigned j) { llvm_unreachable(0); // fall-through case ExternalWeak: - if (F->hasAddressTaken()) + if (F->hasAddressTaken()) ThunkGToF(F, G); else AliasGToF(F, G); - break; + break; case Internal: { bool addrTakenF = F->hasAddressTaken(); bool addrTakenG = G->hasAddressTaken(); if (!addrTakenF && addrTakenG) { std::swap(FnVec[i], FnVec[j]); std::swap(F, G); - std::swap(addrTakenF, addrTakenG); - } + std::swap(addrTakenF, addrTakenG); + } if (addrTakenF && addrTakenG) { ThunkGToF(F, G); @@ -602,7 +602,7 @@ static bool fold(std::vector &FnVec, unsigned i, unsigned j) { assert(!addrTakenG); AliasGToF(F, G); } - } break; + } break; } break; } diff --git a/lib/Transforms/Scalar/GVN.cpp b/lib/Transforms/Scalar/GVN.cpp index 9f72659d215..c36f5e1791e 100644 --- a/lib/Transforms/Scalar/GVN.cpp +++ b/lib/Transforms/Scalar/GVN.cpp @@ -65,14 +65,14 @@ namespace { struct Expression { enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL, UDIV, SDIV, FDIV, UREM, SREM, - FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, - ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, - ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, - FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, - FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, + FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, + ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, + ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, + FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, + FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT, SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI, - FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, + FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT, EMPTY, TOMBSTONE }; @@ -83,10 +83,10 @@ namespace { uint32_t thirdVN; SmallVector varargs; Value* function; - + Expression() { } Expression(ExpressionOpcode o) : opcode(o) { } - + bool operator==(const Expression &other) const { if (opcode != other.opcode) return false; @@ -105,20 +105,20 @@ namespace { else { if (varargs.size() != other.varargs.size()) return false; - + for (size_t i = 0; i < varargs.size(); ++i) if (varargs[i] != other.varargs[i]) return false; - + return true; } } - + bool operator!=(const Expression &other) const { return !(*this == other); } }; - + class ValueTable { private: DenseMap valueNumbering; @@ -126,9 +126,9 @@ namespace { AliasAnalysis* AA; MemoryDependenceAnalysis* MD; DominatorTree* DT; - + uint32_t nextValueNumber; - + Expression::ExpressionOpcode getOpcode(BinaryOperator* BO); Expression::ExpressionOpcode getOpcode(CmpInst* C); Expression::ExpressionOpcode getOpcode(CastInst* C); @@ -164,30 +164,30 @@ template <> struct DenseMapInfo { static inline Expression getEmptyKey() { return Expression(Expression::EMPTY); } - + static inline Expression getTombstoneKey() { return Expression(Expression::TOMBSTONE); } - + static unsigned getHashValue(const Expression e) { unsigned hash = e.opcode; - + hash = e.firstVN + hash * 37; hash = e.secondVN + hash * 37; hash = e.thirdVN + hash * 37; - + hash = ((unsigned)((uintptr_t)e.type >> 4) ^ (unsigned)((uintptr_t)e.type >> 9)) + hash * 37; - + for (SmallVector::const_iterator I = e.varargs.begin(), E = e.varargs.end(); I != E; ++I) hash = *I + hash * 37; - + hash = ((unsigned)((uintptr_t)e.function >> 4) ^ (unsigned)((uintptr_t)e.function >> 9)) + hash * 37; - + return hash; } static bool isEqual(const Expression &LHS, const Expression &RHS) { @@ -284,126 +284,126 @@ Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) { Expression ValueTable::create_expression(CallInst* C) { Expression e; - + e.type = C->getType(); e.firstVN = 0; e.secondVN = 0; e.thirdVN = 0; e.function = C->getCalledFunction(); e.opcode = Expression::CALL; - + for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end(); I != E; ++I) e.varargs.push_back(lookup_or_add(*I)); - + return e; } Expression ValueTable::create_expression(BinaryOperator* BO) { Expression e; - + e.firstVN = lookup_or_add(BO->getOperand(0)); e.secondVN = lookup_or_add(BO->getOperand(1)); e.thirdVN = 0; e.function = 0; e.type = BO->getType(); e.opcode = getOpcode(BO); - + return e; } Expression ValueTable::create_expression(CmpInst* C) { Expression e; - + e.firstVN = lookup_or_add(C->getOperand(0)); e.secondVN = lookup_or_add(C->getOperand(1)); e.thirdVN = 0; e.function = 0; e.type = C->getType(); e.opcode = getOpcode(C); - + return e; } Expression ValueTable::create_expression(CastInst* C) { Expression e; - + e.firstVN = lookup_or_add(C->getOperand(0)); e.secondVN = 0; e.thirdVN = 0; e.function = 0; e.type = C->getType(); e.opcode = getOpcode(C); - + return e; } Expression ValueTable::create_expression(ShuffleVectorInst* S) { Expression e; - + e.firstVN = lookup_or_add(S->getOperand(0)); e.secondVN = lookup_or_add(S->getOperand(1)); e.thirdVN = lookup_or_add(S->getOperand(2)); e.function = 0; e.type = S->getType(); e.opcode = Expression::SHUFFLE; - + return e; } Expression ValueTable::create_expression(ExtractElementInst* E) { Expression e; - + e.firstVN = lookup_or_add(E->getOperand(0)); e.secondVN = lookup_or_add(E->getOperand(1)); e.thirdVN = 0; e.function = 0; e.type = E->getType(); e.opcode = Expression::EXTRACT; - + return e; } Expression ValueTable::create_expression(InsertElementInst* I) { Expression e; - + e.firstVN = lookup_or_add(I->getOperand(0)); e.secondVN = lookup_or_add(I->getOperand(1)); e.thirdVN = lookup_or_add(I->getOperand(2)); e.function = 0; e.type = I->getType(); e.opcode = Expression::INSERT; - + return e; } Expression ValueTable::create_expression(SelectInst* I) { Expression e; - + e.firstVN = lookup_or_add(I->getCondition()); e.secondVN = lookup_or_add(I->getTrueValue()); e.thirdVN = lookup_or_add(I->getFalseValue()); e.function = 0; e.type = I->getType(); e.opcode = Expression::SELECT; - + return e; } Expression ValueTable::create_expression(GetElementPtrInst* G) { Expression e; - + e.firstVN = lookup_or_add(G->getPointerOperand()); e.secondVN = 0; e.thirdVN = 0; e.function = 0; e.type = G->getType(); e.opcode = Expression::GEP; - + for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end(); I != E; ++I) e.varargs.push_back(lookup_or_add(*I)); - + return e; } @@ -422,11 +422,11 @@ uint32_t ValueTable::lookup_or_add(Value* V) { DenseMap::iterator VI = valueNumbering.find(V); if (VI != valueNumbering.end()) return VI->second; - + if (CallInst* C = dyn_cast(V)) { if (AA->doesNotAccessMemory(C)) { Expression e = create_expression(C); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -434,20 +434,20 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (AA->onlyReadsMemory(C)) { Expression e = create_expression(C); - + if (expressionNumbering.find(e) == expressionNumbering.end()) { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); return nextValueNumber++; } - + MemDepResult local_dep = MD->getDependency(C); - + if (!local_dep.isDef() && !local_dep.isNonLocal()) { valueNumbering.insert(std::make_pair(V, nextValueNumber)); return nextValueNumber++; @@ -455,12 +455,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { if (local_dep.isDef()) { CallInst* local_cdep = cast(local_dep.getInst()); - + if (local_cdep->getNumOperands() != C->getNumOperands()) { valueNumbering.insert(std::make_pair(V, nextValueNumber)); return nextValueNumber++; } - + for (unsigned i = 1; i < C->getNumOperands(); ++i) { uint32_t c_vn = lookup_or_add(C->getOperand(i)); uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i)); @@ -469,19 +469,19 @@ uint32_t ValueTable::lookup_or_add(Value* V) { return nextValueNumber++; } } - + uint32_t v = lookup_or_add(local_cdep); valueNumbering.insert(std::make_pair(V, v)); return v; } // Non-local case. - const MemoryDependenceAnalysis::NonLocalDepInfo &deps = + const MemoryDependenceAnalysis::NonLocalDepInfo &deps = MD->getNonLocalCallDependency(CallSite(C)); // FIXME: call/call dependencies for readonly calls should return def, not // clobber! Move the checking logic to MemDep! CallInst* cdep = 0; - + // Check to see if we have a single dominating call instruction that is // identical to C. for (unsigned i = 0, e = deps.size(); i != e; ++i) { @@ -496,23 +496,23 @@ uint32_t ValueTable::lookup_or_add(Value* V) { cdep = 0; break; } - + CallInst *NonLocalDepCall = dyn_cast(I->second.getInst()); // FIXME: All duplicated with non-local case. if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){ cdep = NonLocalDepCall; continue; } - + cdep = 0; break; } - + if (!cdep) { valueNumbering.insert(std::make_pair(V, nextValueNumber)); return nextValueNumber++; } - + if (cdep->getNumOperands() != C->getNumOperands()) { valueNumbering.insert(std::make_pair(V, nextValueNumber)); return nextValueNumber++; @@ -525,18 +525,18 @@ uint32_t ValueTable::lookup_or_add(Value* V) { return nextValueNumber++; } } - + uint32_t v = lookup_or_add(cdep); valueNumbering.insert(std::make_pair(V, v)); return v; - + } else { valueNumbering.insert(std::make_pair(V, nextValueNumber)); return nextValueNumber++; } } else if (BinaryOperator* BO = dyn_cast(V)) { Expression e = create_expression(BO); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -544,12 +544,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (CmpInst* C = dyn_cast(V)) { Expression e = create_expression(C); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -557,12 +557,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (ShuffleVectorInst* U = dyn_cast(V)) { Expression e = create_expression(U); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -570,12 +570,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (ExtractElementInst* U = dyn_cast(V)) { Expression e = create_expression(U); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -583,12 +583,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (InsertElementInst* U = dyn_cast(V)) { Expression e = create_expression(U); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -596,12 +596,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (SelectInst* U = dyn_cast(V)) { Expression e = create_expression(U); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -609,12 +609,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (CastInst* U = dyn_cast(V)) { Expression e = create_expression(U); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -622,12 +622,12 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else if (GetElementPtrInst* U = dyn_cast(V)) { Expression e = create_expression(U); - + DenseMap::iterator EI = expressionNumbering.find(e); if (EI != expressionNumbering.end()) { valueNumbering.insert(std::make_pair(V, EI->second)); @@ -635,7 +635,7 @@ uint32_t ValueTable::lookup_or_add(Value* V) { } else { expressionNumbering.insert(std::make_pair(e, nextValueNumber)); valueNumbering.insert(std::make_pair(V, nextValueNumber)); - + return nextValueNumber++; } } else { @@ -681,7 +681,7 @@ namespace { struct ValueNumberScope { ValueNumberScope* parent; DenseMap table; - + ValueNumberScope(ValueNumberScope* p) : parent(p) { } }; } @@ -700,21 +700,21 @@ namespace { ValueTable VN; DenseMap localAvail; - + typedef DenseMap > PhiMapType; PhiMapType phiMap; - - + + // This transformation requires dominator postdominator info virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired(); AU.addRequired(); AU.addRequired(); - + AU.addPreserved(); AU.addPreserved(); } - + // Helper fuctions // FIXME: eliminate or document these better bool processLoad(LoadInst* L, @@ -736,7 +736,7 @@ namespace { void cleanupGlobalSets(); void verifyRemoved(const Instruction *I) const; }; - + char GVN::ID = 0; } @@ -759,24 +759,24 @@ void GVN::dump(DenseMap& d) { static bool isSafeReplacement(PHINode* p, Instruction* inst) { if (!isa(inst)) return true; - + for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end(); UI != E; ++UI) if (PHINode* use_phi = dyn_cast(UI)) if (use_phi->getParent() == inst->getParent()) return false; - + return true; } Value* GVN::CollapsePhi(PHINode* p) { Value* constVal = p->hasConstantValue(DT); if (!constVal) return 0; - + Instruction* inst = dyn_cast(constVal); if (!inst) return constVal; - + if (DT->dominates(inst, p)) if (isSafeReplacement(p, inst)) return inst; @@ -787,17 +787,17 @@ Value* GVN::CollapsePhi(PHINode* p) { /// available values are in Phis. Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction* orig, DenseMap &Phis, - bool top_level) { - + bool top_level) { + // If we have already computed this value, return the previously computed val. DenseMap::iterator V = Phis.find(BB); if (V != Phis.end() && !top_level) return V->second; - + // If the block is unreachable, just return undef, since this path // can't actually occur at runtime. if (!DT->isReachableFromEntry(BB)) return Phis[BB] = UndefValue::get(orig->getType()); - + if (BasicBlock *Pred = BB->getSinglePredecessor()) { Value *ret = GetValueForBlock(Pred, orig, Phis); Phis[BB] = ret; @@ -812,23 +812,23 @@ Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction* orig, NumPreds = ExistingPN->getNumIncomingValues(); else NumPreds = std::distance(pred_begin(BB), pred_end(BB)); - + // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so // now, then get values to fill in the incoming values for the PHI. PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle", BB->begin()); PN->reserveOperandSpace(NumPreds); - + Phis.insert(std::make_pair(BB, PN)); - + // Fill in the incoming values for the block. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { Value* val = GetValueForBlock(*PI, orig, Phis); PN->addIncoming(val, *PI); } - + VN.getAliasAnalysis()->copyValue(orig, PN); - + // Attempt to collapse PHI nodes that are trivially redundant Value* v = CollapsePhi(PN); if (!v) { @@ -837,10 +837,10 @@ Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction* orig, phiMap[L->getPointerOperand()].insert(PN); else phiMap[orig].insert(PN); - + return PN; } - + PN->replaceAllUsesWith(v); if (isa(v->getType())) MD->invalidateCachedPointerInfo(v); @@ -869,11 +869,11 @@ Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction* orig, /// currently speculating that it will be. /// 3) we are speculating for this block and have used that to speculate for /// other blocks. -static bool IsValueFullyAvailableInBlock(BasicBlock *BB, +static bool IsValueFullyAvailableInBlock(BasicBlock *BB, DenseMap &FullyAvailableBlocks) { // Optimistically assume that the block is fully available and check to see // if we already know about this block in one lookup. - std::pair::iterator, char> IV = + std::pair::iterator, char> IV = FullyAvailableBlocks.insert(std::make_pair(BB, 2)); // If the entry already existed for this block, return the precomputed value. @@ -884,29 +884,29 @@ static bool IsValueFullyAvailableInBlock(BasicBlock *BB, IV.first->second = 3; return IV.first->second != 0; } - + // Otherwise, see if it is fully available in all predecessors. pred_iterator PI = pred_begin(BB), PE = pred_end(BB); - + // If this block has no predecessors, it isn't live-in here. if (PI == PE) goto SpeculationFailure; - + for (; PI != PE; ++PI) // If the value isn't fully available in one of our predecessors, then it // isn't fully available in this block either. Undo our previous // optimistic assumption and bail out. if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks)) goto SpeculationFailure; - + return true; - + // SpeculationFailure - If we get here, we found out that this is not, after // all, a fully-available block. We have a problem if we speculated on this and // used the speculation to mark other blocks as available. SpeculationFailure: char &BBVal = FullyAvailableBlocks[BB]; - + // If we didn't speculate on this, just return with it set to false. if (BBVal == 2) { BBVal = 0; @@ -918,7 +918,7 @@ SpeculationFailure: // 0 if set to one. SmallVector BBWorklist; BBWorklist.push_back(BB); - + while (!BBWorklist.empty()) { BasicBlock *Entry = BBWorklist.pop_back_val(); // Note that this sets blocks to 0 (unavailable) if they happen to not @@ -928,11 +928,11 @@ SpeculationFailure: // Mark as unavailable. EntryVal = 0; - + for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I) BBWorklist.push_back(*I); } - + return false; } @@ -941,12 +941,12 @@ SpeculationFailure: bool GVN::processNonLocalLoad(LoadInst *LI, SmallVectorImpl &toErase) { // Find the non-local dependencies of the load. - SmallVector Deps; + SmallVector Deps; MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(), Deps); //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: " // << Deps.size() << *LI << '\n'); - + // If we had to process more than one hundred blocks to find the // dependencies, this load isn't worth worrying about. Optimizing // it will be too expensive. @@ -963,34 +963,34 @@ bool GVN::processNonLocalLoad(LoadInst *LI, ); return false; } - + // Filter out useless results (non-locals, etc). Keep track of the blocks // where we have a value available in repl, also keep track of whether we see // dependencies that produce an unknown value for the load (such as a call // that could potentially clobber the load). SmallVector, 16> ValuesPerBlock; SmallVector UnavailableBlocks; - + for (unsigned i = 0, e = Deps.size(); i != e; ++i) { BasicBlock *DepBB = Deps[i].first; MemDepResult DepInfo = Deps[i].second; - + if (DepInfo.isClobber()) { UnavailableBlocks.push_back(DepBB); continue; } - + Instruction *DepInst = DepInfo.getInst(); - + // Loading the allocation -> undef. if (isa(DepInst) || isMalloc(DepInst)) { - ValuesPerBlock.push_back(std::make_pair(DepBB, + ValuesPerBlock.push_back(std::make_pair(DepBB, UndefValue::get(LI->getType()))); continue; } - + if (StoreInst* S = dyn_cast(DepInst)) { - // Reject loads and stores that are to the same address but are of + // Reject loads and stores that are to the same address but are of // different types. // NOTE: 403.gcc does have this case (e.g. in readonly_fields_p) because // of bitfield access, it would be interesting to optimize for it at some @@ -999,9 +999,9 @@ bool GVN::processNonLocalLoad(LoadInst *LI, UnavailableBlocks.push_back(DepBB); continue; } - + ValuesPerBlock.push_back(std::make_pair(DepBB, S->getOperand(0))); - + } else if (LoadInst* LD = dyn_cast(DepInst)) { if (LD->getType() != LI->getType()) { UnavailableBlocks.push_back(DepBB); @@ -1013,11 +1013,11 @@ bool GVN::processNonLocalLoad(LoadInst *LI, continue; } } - + // If we have no predecessors that produce a known value for this load, exit // early. if (ValuesPerBlock.empty()) return false; - + // If all of the instructions we depend on produce a known value for this // load, then it is fully redundant and we can use PHI insertion to compute // its value. Insert PHIs and remove the fully redundant value now. @@ -1036,18 +1036,18 @@ bool GVN::processNonLocalLoad(LoadInst *LI, NumGVNLoad++; return true; } - + ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I)); } - + DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n'); - + DenseMap BlockReplValues; BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end()); // Perform PHI construction. Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true); LI->replaceAllUsesWith(v); - + if (isa(v)) v->takeName(LI); if (isa(v->getType())) @@ -1056,7 +1056,7 @@ bool GVN::processNonLocalLoad(LoadInst *LI, NumGVNLoad++; return true; } - + if (!EnablePRE || !EnableLoadPRE) return false; @@ -1067,7 +1067,7 @@ bool GVN::processNonLocalLoad(LoadInst *LI, // prefer to not increase code size. As such, we only do this when we know // that we only have to insert *one* load (which means we're basically moving // the load, not inserting a new one). - + SmallPtrSet Blockers; for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i) Blockers.insert(UnavailableBlocks[i]); @@ -1091,10 +1091,10 @@ bool GVN::processNonLocalLoad(LoadInst *LI, if (TmpBB->getTerminator()->getNumSuccessors() != 1) allSingleSucc = false; } - + assert(TmpBB); LoadBB = TmpBB; - + // If we have a repl set with LI itself in it, this means we have a loop where // at least one of the values is LI. Since this means that we won't be able // to eliminate LI even if we insert uses in the other predecessors, we will @@ -1102,17 +1102,17 @@ bool GVN::processNonLocalLoad(LoadInst *LI, for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) if (ValuesPerBlock[i].second == LI) return false; - + if (isSinglePred) { bool isHot = false; for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) if (Instruction *I = dyn_cast(ValuesPerBlock[i].second)) - // "Hot" Instruction is in some loop (because it dominates its dep. - // instruction). - if (DT->dominates(LI, I)) { - isHot = true; - break; - } + // "Hot" Instruction is in some loop (because it dominates its dep. + // instruction). + if (DT->dominates(LI, I)) { + isHot = true; + break; + } // We are interested only in "hot" instructions. We don't want to do any // mis-optimizations here. @@ -1137,20 +1137,20 @@ bool GVN::processNonLocalLoad(LoadInst *LI, PI != E; ++PI) { if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks)) continue; - + // If this load is not available in multiple predecessors, reject it. if (UnavailablePred && UnavailablePred != *PI) return false; UnavailablePred = *PI; } - + assert(UnavailablePred != 0 && "Fully available value should be eliminated above!"); - + // If the loaded pointer is PHI node defined in this block, do PHI translation // to get its value in the predecessor. Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred); - + // Make sure the value is live in the predecessor. If it was defined by a // non-PHI instruction in this block, we don't know how to recompute it above. if (Instruction *LPInst = dyn_cast(LoadPtr)) @@ -1159,7 +1159,7 @@ bool GVN::processNonLocalLoad(LoadInst *LI, << *LPInst << '\n' << *LI << "\n"); return false; } - + // We don't currently handle critical edges :( if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) { DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '" @@ -1184,20 +1184,20 @@ bool GVN::processNonLocalLoad(LoadInst *LI, // and using PHI construction to get the value in the other predecessors, do // it. DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n'); - + Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false, LI->getAlignment(), UnavailablePred->getTerminator()); - + SmallPtrSet &p = phiMap[LI->getPointerOperand()]; for (SmallPtrSet::iterator I = p.begin(), E = p.end(); I != E; ++I) ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I)); - + DenseMap BlockReplValues; BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end()); BlockReplValues[UnavailablePred] = NewLoad; - + // Perform PHI construction. Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true); LI->replaceAllUsesWith(v); @@ -1215,12 +1215,12 @@ bool GVN::processNonLocalLoad(LoadInst *LI, bool GVN::processLoad(LoadInst *L, SmallVectorImpl &toErase) { if (L->isVolatile()) return false; - + Value* pointer = L->getPointerOperand(); // ... to a pointer that has been loaded from before... MemDepResult dep = MD->getDependency(L); - + // If the value isn't available, don't do anything! if (dep.isClobber()) { DEBUG( @@ -1243,7 +1243,7 @@ bool GVN::processLoad(LoadInst *L, SmallVectorImpl &toErase) { // FIXME: Could do better! if (DepSI->getPointerOperand()->getType() != pointer->getType()) return false; - + // Remove it! L->replaceAllUsesWith(DepSI->getOperand(0)); if (isa(DepSI->getOperand(0)->getType())) @@ -1258,7 +1258,7 @@ bool GVN::processLoad(LoadInst *L, SmallVectorImpl &toErase) { // FIXME: Could do better! load i32 -> load i8 -> truncate on little endian. if (DepLI->getType() != L->getType()) return false; - + // Remove it! L->replaceAllUsesWith(DepLI); if (isa(DepLI->getType())) @@ -1267,7 +1267,7 @@ bool GVN::processLoad(LoadInst *L, SmallVectorImpl &toErase) { NumGVNLoad++; return true; } - + // If this load really doesn't depend on anything, then we must be loading an // undef value. This can happen when loading for a fresh allocation with no // intervening stores, for example. @@ -1285,9 +1285,9 @@ Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) { DenseMap::iterator I = localAvail.find(BB); if (I == localAvail.end()) return 0; - + ValueNumberScope* locals = I->second; - + while (locals) { DenseMap::iterator I = locals->table.find(num); if (I != locals->table.end()) @@ -1295,57 +1295,57 @@ Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) { else locals = locals->parent; } - + return 0; } /// AttemptRedundancyElimination - If the "fast path" of redundancy elimination -/// by inheritance from the dominator fails, see if we can perform phi +/// by inheritance from the dominator fails, see if we can perform phi /// construction to eliminate the redundancy. Value* GVN::AttemptRedundancyElimination(Instruction* orig, unsigned valno) { BasicBlock* BaseBlock = orig->getParent(); - + SmallPtrSet Visited; SmallVector Stack; Stack.push_back(BaseBlock); - + DenseMap Results; - + // Walk backwards through our predecessors, looking for instances of the // value number we're looking for. Instances are recorded in the Results // map, which is then used to perform phi construction. while (!Stack.empty()) { BasicBlock* Current = Stack.back(); Stack.pop_back(); - + // If we've walked all the way to a proper dominator, then give up. Cases // where the instance is in the dominator will have been caught by the fast // path, and any cases that require phi construction further than this are // probably not worth it anyways. Note that this is a SIGNIFICANT compile // time improvement. if (DT->properlyDominates(Current, orig->getParent())) return 0; - + DenseMap::iterator LA = localAvail.find(Current); if (LA == localAvail.end()) return 0; DenseMap::iterator V = LA->second->table.find(valno); - + if (V != LA->second->table.end()) { // Found an instance, record it. Results.insert(std::make_pair(Current, V->second)); continue; } - + // If we reach the beginning of the function, then give up. if (pred_begin(Current) == pred_end(Current)) return 0; - + for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current); PI != PE; ++PI) if (Visited.insert(*PI)) Stack.push_back(*PI); } - + // If we didn't find instances, give up. Otherwise, perform phi construction. if (Results.size() == 0) return 0; @@ -1359,71 +1359,71 @@ bool GVN::processInstruction(Instruction *I, SmallVectorImpl &toErase) { if (LoadInst* L = dyn_cast(I)) { bool changed = processLoad(L, toErase); - + if (!changed) { unsigned num = VN.lookup_or_add(L); localAvail[I->getParent()]->table.insert(std::make_pair(num, L)); } - + return changed; } - + uint32_t nextNum = VN.getNextUnusedValueNumber(); unsigned num = VN.lookup_or_add(I); - + if (BranchInst* BI = dyn_cast(I)) { localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); - + if (!BI->isConditional() || isa(BI->getCondition())) return false; - + Value* branchCond = BI->getCondition(); uint32_t condVN = VN.lookup_or_add(branchCond); - + BasicBlock* trueSucc = BI->getSuccessor(0); BasicBlock* falseSucc = BI->getSuccessor(1); - + if (trueSucc->getSinglePredecessor()) - localAvail[trueSucc]->table[condVN] = + localAvail[trueSucc]->table[condVN] = ConstantInt::getTrue(trueSucc->getContext()); if (falseSucc->getSinglePredecessor()) localAvail[falseSucc]->table[condVN] = ConstantInt::getFalse(trueSucc->getContext()); return false; - + // Allocations are always uniquely numbered, so we can save time and memory - // by fast failing them. + // by fast failing them. } else if (isa(I) || isMalloc(I) || isa(I)) { localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); return false; } - + // Collapse PHI nodes if (PHINode* p = dyn_cast(I)) { Value* constVal = CollapsePhi(p); - + if (constVal) { for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end(); PI != PE; ++PI) PI->second.erase(p); - + p->replaceAllUsesWith(constVal); if (isa(constVal->getType())) MD->invalidateCachedPointerInfo(constVal); VN.erase(p); - + toErase.push_back(p); } else { localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); } - + // If the number we were assigned was a brand new VN, then we don't // need to do a lookup to see if the number already exists // somewhere in the domtree: it can't! } else if (num == nextNum) { localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); - + // Perform fast-path value-number based elimination of values inherited from // dominators. } else if (Value* repl = lookupNumber(I->getParent(), num)) { @@ -1449,7 +1449,7 @@ bool GVN::processInstruction(Instruction *I, } else { localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); } - + return false; } @@ -1460,10 +1460,10 @@ bool GVN::runOnFunction(Function& F) { VN.setAliasAnalysis(&getAnalysis()); VN.setMemDep(MD); VN.setDomTree(DT); - + bool changed = false; bool shouldContinue = true; - + // Merge unconditional branches, allowing PRE to catch more // optimization opportunities. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) { @@ -1471,19 +1471,19 @@ bool GVN::runOnFunction(Function& F) { ++FI; bool removedBlock = MergeBlockIntoPredecessor(BB, this); if (removedBlock) NumGVNBlocks++; - + changed |= removedBlock; } - + unsigned Iteration = 0; - + while (shouldContinue) { DEBUG(errs() << "GVN iteration: " << Iteration << "\n"); shouldContinue = iterateOnFunction(F); changed |= shouldContinue; ++Iteration; } - + if (EnablePRE) { bool PREChanged = true; while (PREChanged) { @@ -1507,7 +1507,7 @@ bool GVN::processBlock(BasicBlock* BB) { // incrementing BI before processing an instruction). SmallVector toErase; bool changed_function = false; - + for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { changed_function |= processInstruction(BI, toErase); @@ -1515,10 +1515,10 @@ bool GVN::processBlock(BasicBlock* BB) { ++BI; continue; } - + // If we need some instructions deleted, do it now. NumGVNInstr += toErase.size(); - + // Avoid iterator invalidation. bool AtStart = BI == BB->begin(); if (!AtStart) @@ -1538,7 +1538,7 @@ bool GVN::processBlock(BasicBlock* BB) { else ++BI; } - + return changed_function; } @@ -1551,10 +1551,10 @@ bool GVN::performPRE(Function& F) { for (df_iterator DI = df_begin(&F.getEntryBlock()), DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) { BasicBlock* CurrentBlock = *DI; - + // Nothing to PRE in the entry block. if (CurrentBlock == &F.getEntryBlock()) continue; - + for (BasicBlock::iterator BI = CurrentBlock->begin(), BE = CurrentBlock->end(); BI != BE; ) { Instruction *CurInst = BI++; @@ -1567,7 +1567,7 @@ bool GVN::performPRE(Function& F) { continue; uint32_t valno = VN.lookup(CurInst); - + // Look for the predecessors for PRE opportunities. We're // only trying to solve the basic diamond case, where // a value is computed in the successor and one predecessor, @@ -1591,8 +1591,8 @@ bool GVN::performPRE(Function& F) { numWithout = 2; break; } - - DenseMap::iterator predV = + + DenseMap::iterator predV = localAvail[*PI]->table.find(valno); if (predV == localAvail[*PI]->table.end()) { PREPred = *PI; @@ -1604,12 +1604,12 @@ bool GVN::performPRE(Function& F) { numWith++; } } - + // Don't do PRE when it might increase code size, i.e. when // we would need to insert instructions in more than one pred. if (numWithout != 1 || numWith == 0) continue; - + // We can't do PRE safely on a critical edge, so instead we schedule // the edge to be split and perform the PRE the next time we iterate // on the function. @@ -1620,12 +1620,12 @@ bool GVN::performPRE(Function& F) { succNum = i; break; } - + if (isCriticalEdge(PREPred->getTerminator(), succNum)) { toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum)); continue; } - + // Instantiate the expression the in predecessor that lacked it. // Because we are going top-down through the block, all value numbers // will be available in the predecessor by the time we need them. Any @@ -1637,7 +1637,7 @@ bool GVN::performPRE(Function& F) { Value *Op = PREInstr->getOperand(i); if (isa(Op) || isa(Op) || isa(Op)) continue; - + if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) { PREInstr->setOperand(i, V); } else { @@ -1645,25 +1645,25 @@ bool GVN::performPRE(Function& F) { break; } } - + // Fail out if we encounter an operand that is not available in - // the PRE predecessor. This is typically because of loads which + // the PRE predecessor. This is typically because of loads which // are not value numbered precisely. if (!success) { delete PREInstr; DEBUG(verifyRemoved(PREInstr)); continue; } - + PREInstr->insertBefore(PREPred->getTerminator()); PREInstr->setName(CurInst->getName() + ".pre"); predMap[PREPred] = PREInstr; VN.add(PREInstr, valno); NumGVNPRE++; - + // Update the availability map to include the new instruction. localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr)); - + // Create a PHI to make the value available in this block. PHINode* Phi = PHINode::Create(CurInst->getType(), CurInst->getName() + ".pre-phi", @@ -1671,15 +1671,15 @@ bool GVN::performPRE(Function& F) { for (pred_iterator PI = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock); PI != PE; ++PI) Phi->addIncoming(predMap[*PI], *PI); - + VN.add(Phi, valno); localAvail[CurrentBlock]->table[valno] = Phi; - + CurInst->replaceAllUsesWith(Phi); if (isa(Phi->getType())) MD->invalidateCachedPointerInfo(Phi); VN.erase(CurInst); - + DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n'); MD->removeInstruction(CurInst); CurInst->eraseFromParent(); @@ -1687,11 +1687,11 @@ bool GVN::performPRE(Function& F) { Changed = true; } } - + for (SmallVector, 4>::iterator I = toSplit.begin(), E = toSplit.end(); I != E; ++I) SplitCriticalEdge(I->first, I->second, this); - + return Changed || toSplit.size(); } diff --git a/lib/VMCore/AsmWriter.cpp b/lib/VMCore/AsmWriter.cpp index 12436523b16..0d52e1fc7fa 100644 --- a/lib/VMCore/AsmWriter.cpp +++ b/lib/VMCore/AsmWriter.cpp @@ -50,15 +50,15 @@ AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} static const Module *getModuleFromVal(const Value *V) { if (const Argument *MA = dyn_cast(V)) return MA->getParent() ? MA->getParent()->getParent() : 0; - + if (const BasicBlock *BB = dyn_cast(V)) return BB->getParent() ? BB->getParent()->getParent() : 0; - + if (const Instruction *I = dyn_cast(V)) { const Function *M = I->getParent() ? I->getParent()->getParent() : 0; return M ? M->getParent() : 0; } - + if (const GlobalValue *GV = dyn_cast(V)) return GV->getParent(); return 0; @@ -97,7 +97,7 @@ static void PrintLLVMName(raw_ostream &OS, const StringRef &Name, case LabelPrefix: break; case LocalPrefix: OS << '%'; break; } - + // Scan the name to see if it needs quotes first. bool NeedsQuotes = isdigit(Name[0]); if (!NeedsQuotes) { @@ -109,13 +109,13 @@ static void PrintLLVMName(raw_ostream &OS, const StringRef &Name, } } } - + // If we didn't need any quotes, just write out the name in one blast. if (!NeedsQuotes) { OS << Name; return; } - + // Okay, we need quotes. Output the quotes and escape any scary characters as // needed. OS << '"'; @@ -127,7 +127,7 @@ static void PrintLLVMName(raw_ostream &OS, const StringRef &Name, /// prefixed with % (if the string only contains simple characters) or is /// surrounded with ""'s (if it has special chars in it). Print it out. static void PrintLLVMName(raw_ostream &OS, const Value *V) { - PrintLLVMName(OS, V->getName(), + PrintLLVMName(OS, V->getName(), isa(V) ? GlobalPrefix : LocalPrefix); } @@ -174,11 +174,11 @@ void TypePrinting::CalcTypeName(const Type *Ty, return; } } - + // Check to see if the Type is already on the stack... unsigned Slot = 0, CurSize = TypeStack.size(); while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type - + // This is another base case for the recursion. In this case, we know // that we have looped back to a type that we have previously visited. // Generate the appropriate upreference to handle this. @@ -186,9 +186,9 @@ void TypePrinting::CalcTypeName(const Type *Ty, OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference return; } - + TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. - + switch (Ty->getTypeID()) { case Type::VoidTyID: OS << "void"; break; case Type::FloatTyID: OS << "float"; break; @@ -201,7 +201,7 @@ void TypePrinting::CalcTypeName(const Type *Ty, case Type::IntegerTyID: OS << 'i' << cast(Ty)->getBitWidth(); break; - + case Type::FunctionTyID: { const FunctionType *FTy = cast(Ty); CalcTypeName(FTy->getReturnType(), TypeStack, OS); @@ -265,7 +265,7 @@ void TypePrinting::CalcTypeName(const Type *Ty, OS << ""; break; } - + TypeStack.pop_back(); // Remove self from stack. } @@ -283,13 +283,13 @@ void TypePrinting::print(const Type *Ty, raw_ostream &OS, return; } } - + // Otherwise we have a type that has not been named but is a derived type. // Carefully recurse the type hierarchy to print out any contained symbolic // names. SmallVector TypeStack; std::string TypeName; - + raw_string_ostream TypeOS(TypeName); CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName); OS << TypeOS.str(); @@ -305,13 +305,13 @@ namespace { // objects, we keep several helper maps. DenseSet VisitedConstants; DenseSet VisitedTypes; - + TypePrinting &TP; std::vector &NumberedTypes; public: TypeFinder(TypePrinting &tp, std::vector &numberedTypes) : TP(tp), NumberedTypes(numberedTypes) {} - + void Run(const Module &M) { // Get types from the type symbol table. This gets opaque types referened // only through derived named types. @@ -319,7 +319,7 @@ namespace { for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); TI != E; ++TI) IncorporateType(TI->second); - + // Get types from global variables. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { @@ -327,18 +327,18 @@ namespace { if (I->hasInitializer()) IncorporateValue(I->getInitializer()); } - + // Get types from aliases. for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E; ++I) { IncorporateType(I->getType()); IncorporateValue(I->getAliasee()); } - + // Get types from functions. for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) { IncorporateType(FI->getType()); - + for (Function::const_iterator BB = FI->begin(), E = FI->end(); BB != E;++BB) for (BasicBlock::const_iterator II = BB->begin(), @@ -352,40 +352,40 @@ namespace { } } } - + private: void IncorporateType(const Type *Ty) { // Check to see if we're already visited this type. if (!VisitedTypes.insert(Ty).second) return; - + // If this is a structure or opaque type, add a name for the type. if (((isa(Ty) && cast(Ty)->getNumElements()) || isa(Ty)) && !TP.hasTypeName(Ty)) { TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size()))); NumberedTypes.push_back(Ty); } - + // Recursively walk all contained types. for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); I != E; ++I) - IncorporateType(*I); + IncorporateType(*I); } - + /// IncorporateValue - This method is used to walk operand lists finding /// types hiding in constant expressions and other operands that won't be /// walked in other ways. GlobalValues, basic blocks, instructions, and /// inst operands are all explicitly enumerated. void IncorporateValue(const Value *V) { if (V == 0 || !isa(V) || isa(V)) return; - + // Already visited? if (!VisitedConstants.insert(V).second) return; - + // Check this type. IncorporateType(V->getType()); - + // Look in operands for types. const Constant *C = cast(V); for (Constant::const_op_iterator I = C->op_begin(), @@ -399,18 +399,18 @@ namespace { /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in /// the specified module to the TypePrinter and all numbered types to it and the /// NumberedTypes table. -static void AddModuleTypesToPrinter(TypePrinting &TP, +static void AddModuleTypesToPrinter(TypePrinting &TP, std::vector &NumberedTypes, const Module *M) { if (M == 0) return; - + // If the module has a symbol table, take all global types and stuff their // names into the TypeNames map. const TypeSymbolTable &ST = M->getTypeSymbolTable(); for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); TI != E; ++TI) { const Type *Ty = cast(TI->second); - + // As a heuristic, don't insert pointer to primitive types, because // they are used too often to have a single useful name. if (const PointerType *PTy = dyn_cast(Ty)) { @@ -419,11 +419,11 @@ static void AddModuleTypesToPrinter(TypePrinting &TP, !isa(PETy)) continue; } - + // Likewise don't insert primitives either. if (Ty->isInteger() || Ty->isPrimitiveType()) continue; - + // Get the name as a string and insert it into TypeNames. std::string NameStr; raw_string_ostream NameROS(NameStr); @@ -432,7 +432,7 @@ static void AddModuleTypesToPrinter(TypePrinting &TP, NameOS.flush(); TP.addTypeName(Ty, NameStr); } - + // Walk the entire module to find references to unnamed structure and opaque // types. This is required for correctness by opaque types (because multiple // uses of an unnamed opaque type needs to be referred to by the same ID) and @@ -464,15 +464,15 @@ class SlotTracker { public: /// ValueMap - A mapping of Values to slot numbers. typedef DenseMap ValueMap; - -private: + +private: /// TheModule - The module for which we are holding slot numbers. const Module* TheModule; - + /// TheFunction - The function for which we are holding slot numbers. const Function* TheFunction; bool FunctionProcessed; - + /// TheMDNode - The MDNode for which we are holding slot numbers. const MDNode *TheMDNode; @@ -482,11 +482,11 @@ private: /// mMap - The TypePlanes map for the module level data. ValueMap mMap; unsigned mNext; - + /// fMap - The TypePlanes map for the function level data. ValueMap fMap; unsigned fNext; - + /// mdnMap - Map for MDNodes. ValueMap mdnMap; unsigned mdnNext; @@ -561,22 +561,22 @@ private: static SlotTracker *createSlotTracker(const Value *V) { if (const Argument *FA = dyn_cast(V)) return new SlotTracker(FA->getParent()); - + if (const Instruction *I = dyn_cast(V)) return new SlotTracker(I->getParent()->getParent()); - + if (const BasicBlock *BB = dyn_cast(V)) return new SlotTracker(BB->getParent()); - + if (const GlobalVariable *GV = dyn_cast(V)) return new SlotTracker(GV->getParent()); - + if (const GlobalAlias *GA = dyn_cast(V)) - return new SlotTracker(GA->getParent()); - + return new SlotTracker(GA->getParent()); + if (const Function *Func = dyn_cast(V)) return new SlotTracker(Func); - + return 0; } @@ -617,7 +617,7 @@ inline void SlotTracker::initialize() { processModule(); TheModule = 0; ///< Prevent re-processing next time we're called. } - + if (TheFunction && !FunctionProcessed) processFunction(); @@ -632,20 +632,20 @@ inline void SlotTracker::initialize() { // variable initializers and create slots for them. void SlotTracker::processModule() { ST_DEBUG("begin processModule!\n"); - + // Add all of the unnamed global variables to the value table. for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end(); I != E; ++I) { - if (!I->hasName()) + if (!I->hasName()) CreateModuleSlot(I); if (I->hasInitializer()) { - if (MDNode *N = dyn_cast(I->getInitializer())) + if (MDNode *N = dyn_cast(I->getInitializer())) CreateMetadataSlot(N); } } - + // Add metadata used by named metadata. - for (Module::const_named_metadata_iterator + for (Module::const_named_metadata_iterator I = TheModule->named_metadata_begin(), E = TheModule->named_metadata_end(); I != E; ++I) { const NamedMDNode *NMD = I; @@ -661,7 +661,7 @@ void SlotTracker::processModule() { I != E; ++I) if (!I->hasName()) CreateModuleSlot(I); - + ST_DEBUG("end processModule!\n"); } @@ -669,15 +669,15 @@ void SlotTracker::processModule() { void SlotTracker::processFunction() { ST_DEBUG("begin processFunction!\n"); fNext = 0; - + // Add all the function arguments with no names. for(Function::const_arg_iterator AI = TheFunction->arg_begin(), AE = TheFunction->arg_end(); AI != AE; ++AI) if (!AI->hasName()) CreateFunctionSlot(AI); - + ST_DEBUG("Inserting Instructions:\n"); - + Metadata &TheMetadata = TheFunction->getContext().getMetadata(); // Add all of the basic blocks and instructions with no names. @@ -685,27 +685,27 @@ void SlotTracker::processFunction() { E = TheFunction->end(); BB != E; ++BB) { if (!BB->hasName()) CreateFunctionSlot(BB); - for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; + for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { if (I->getType() != Type::getVoidTy(TheFunction->getContext()) && !I->hasName()) CreateFunctionSlot(I); - for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) + for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) if (MDNode *N = dyn_cast_or_null(I->getOperand(i))) CreateMetadataSlot(N); - + // Process metadata attached with this instruction. const Metadata::MDMapTy *MDs = TheMetadata.getMDs(I); if (MDs) - for (Metadata::MDMapTy::const_iterator MI = MDs->begin(), - ME = MDs->end(); MI != ME; ++MI) - if (MDNode *MDN = dyn_cast_or_null(MI->second)) - CreateMetadataSlot(MDN); + for (Metadata::MDMapTy::const_iterator MI = MDs->begin(), + ME = MDs->end(); MI != ME; ++MI) + if (MDNode *MDN = dyn_cast_or_null(MI->second)) + CreateMetadataSlot(MDN); } } FunctionProcessed = true; - + ST_DEBUG("end processFunction!\n"); } @@ -746,7 +746,7 @@ void SlotTracker::purgeFunction() { int SlotTracker::getGlobalSlot(const GlobalValue *V) { // Check for uninitialized state and do lazy initialization. initialize(); - + // Find the type plane in the module map ValueMap::iterator MI = mMap.find(V); return MI == mMap.end() ? -1 : (int)MI->second; @@ -756,7 +756,7 @@ int SlotTracker::getGlobalSlot(const GlobalValue *V) { int SlotTracker::getMetadataSlot(const MDNode *N) { // Check for uninitialized state and do lazy initialization. initialize(); - + // Find the type plane in the module map ValueMap::iterator MI = mdnMap.find(N); return MI == mdnMap.end() ? -1 : (int)MI->second; @@ -766,10 +766,10 @@ int SlotTracker::getMetadataSlot(const MDNode *N) { /// getLocalSlot - Get the slot number for a value that is local to a function. int SlotTracker::getLocalSlot(const Value *V) { assert(!isa(V) && "Can't get a constant or global slot with this!"); - + // Check for uninitialized state and do lazy initialization. initialize(); - + ValueMap::iterator FI = fMap.find(V); return FI == fMap.end() ? -1 : (int)FI->second; } @@ -778,13 +778,13 @@ int SlotTracker::getLocalSlot(const Value *V) { /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. void SlotTracker::CreateModuleSlot(const GlobalValue *V) { assert(V && "Can't insert a null Value into SlotTracker!"); - assert(V->getType() != Type::getVoidTy(V->getContext()) && + assert(V->getType() != Type::getVoidTy(V->getContext()) && "Doesn't need a slot!"); assert(!V->hasName() && "Doesn't need a slot!"); - + unsigned DestSlot = mNext++; mMap[V] = DestSlot; - + ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << DestSlot << " ["); // G = Global, F = Function, A = Alias, o = other @@ -795,21 +795,21 @@ void SlotTracker::CreateModuleSlot(const GlobalValue *V) { /// CreateSlot - Create a new slot for the specified value if it has no name. void SlotTracker::CreateFunctionSlot(const Value *V) { - assert(V->getType() != Type::getVoidTy(TheFunction->getContext()) && + assert(V->getType() != Type::getVoidTy(TheFunction->getContext()) && !V->hasName() && "Doesn't need a slot!"); - + unsigned DestSlot = fNext++; fMap[V] = DestSlot; - + // G = Global, F = Function, o = other ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << DestSlot << " [o]\n"); -} +} /// CreateModuleSlot - Insert the specified MDNode* into the slot table. void SlotTracker::CreateMetadataSlot(const MDNode *N) { assert(N && "Can't insert a null Value into SlotTracker!"); - + ValueMap::iterator I = mdnMap.find(N); if (I != mdnMap.end()) return; @@ -817,11 +817,11 @@ void SlotTracker::CreateMetadataSlot(const MDNode *N) { unsigned DestSlot = mdnNext++; mdnMap[N] = DestSlot; - for (MDNode::const_elem_iterator MDI = N->elem_begin(), + for (MDNode::const_elem_iterator MDI = N->elem_begin(), MDE = N->elem_end(); MDI != MDE; ++MDI) { const Value *TV = *MDI; if (TV) - if (const MDNode *N2 = dyn_cast(TV)) + if (const MDNode *N2 = dyn_cast(TV)) CreateMetadataSlot(N2); } } @@ -873,15 +873,15 @@ static void WriteMDNodes(formatted_raw_ostream &Out, TypePrinting &TypePrinter, SlotTracker &Machine) { SmallVector Nodes; Nodes.resize(Machine.mdnSize()); - for (SlotTracker::ValueMap::iterator I = - Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) + for (SlotTracker::ValueMap::iterator I = + Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) Nodes[I->second] = cast(I->first); for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { Out << '!' << i << " = metadata "; const MDNode *Node = Nodes[i]; Out << "!{"; - for (MDNode::const_elem_iterator NI = Node->elem_begin(), + for (MDNode::const_elem_iterator NI = Node->elem_begin(), NE = Node->elem_end(); NI != NE;) { const Value *V = *NI; if (!V) @@ -928,7 +928,7 @@ static void WriteConstantInt(raw_ostream &Out, const Constant *CV, Out << CI->getValue(); return; } - + if (const ConstantFP *CFP = dyn_cast(CV)) { if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble || &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) { @@ -966,14 +966,14 @@ static void WriteConstantInt(raw_ostream &Out, const Constant *CV, APFloat apf = CFP->getValueAPF(); // Floats are represented in ASCII IR as double, convert. if (!isDouble) - apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, + apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored); - Out << "0x" << - utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), + Out << "0x" << + utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), Buffer+40); return; } - + // Some form of long double. These appear as a magic letter identifying // the type, then a fixed number of hex digits. Out << "0x"; @@ -1026,12 +1026,12 @@ static void WriteConstantInt(raw_ostream &Out, const Constant *CV, } return; } - + if (isa(CV)) { Out << "zeroinitializer"; return; } - + if (const ConstantArray *CA = dyn_cast(CV)) { // As a special case, print the array as a string if it is an array of // i8 with ConstantInt values. @@ -1059,7 +1059,7 @@ static void WriteConstantInt(raw_ostream &Out, const Constant *CV, } return; } - + if (const ConstantStruct *CS = dyn_cast(CV)) { if (CS->getType()->isPacked()) Out << '<'; @@ -1081,13 +1081,13 @@ static void WriteConstantInt(raw_ostream &Out, const Constant *CV, } Out << ' '; } - + Out << '}'; if (CS->getType()->isPacked()) Out << '>'; return; } - + if (const ConstantVector *CP = dyn_cast(CV)) { const Type *ETy = CP->getType()->getElementType(); assert(CP->getNumOperands() > 0 && @@ -1105,17 +1105,17 @@ static void WriteConstantInt(raw_ostream &Out, const Constant *CV, Out << '>'; return; } - + if (isa(CV)) { Out << "null"; return; } - + if (isa(CV)) { Out << "undef"; return; } - + if (const MDNode *Node = dyn_cast(CV)) { Out << "!" << Machine->getMetadataSlot(Node); return; @@ -1150,7 +1150,7 @@ static void WriteConstantInt(raw_ostream &Out, const Constant *CV, Out << ')'; return; } - + Out << ""; } @@ -1166,14 +1166,14 @@ static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, PrintLLVMName(Out, V); return; } - + const Constant *CV = dyn_cast(V); if (CV && !isa(CV)) { assert(TypePrinter && "Constants require TypePrinting!"); WriteConstantInt(Out, CV, *TypePrinter, Machine); return; } - + if (const InlineAsm *IA = dyn_cast(V)) { Out << "asm "; if (IA->hasSideEffects()) @@ -1221,7 +1221,7 @@ static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, Slot = -1; } } - + if (Slot != -1) Out << Prefix << Slot; else @@ -1275,7 +1275,7 @@ public: } void write(const Module *M) { printModule(M); } - + void write(const GlobalValue *G) { if (const GlobalVariable *GV = dyn_cast(G)) printGlobal(GV); @@ -1286,7 +1286,7 @@ public: else llvm_unreachable("Unknown global"); } - + void write(const BasicBlock *BB) { printBasicBlock(BB); } void write(const Instruction *I) { printInstruction(*I); } @@ -1322,7 +1322,7 @@ void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { } } -void AssemblyWriter::writeParamOperand(const Value *Operand, +void AssemblyWriter::writeParamOperand(const Value *Operand, Attributes Attrs) { if (Operand == 0) { Out << ""; @@ -1370,7 +1370,7 @@ void AssemblyWriter::printModule(const Module *M) { PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out); Out << "\"\n"; } - + // Loop over the dependent libraries and emit them. Module::lib_iterator LI = M->lib_begin(); Module::lib_iterator LE = M->lib_end(); @@ -1395,7 +1395,7 @@ void AssemblyWriter::printModule(const Module *M) { for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) printGlobal(I); - + // Output all aliases. if (!M->alias_empty()) Out << "\n"; for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); @@ -1466,7 +1466,7 @@ void AssemblyWriter::printGlobal(const GlobalVariable *GV) { if (!GV->hasInitializer() && GV->hasExternalLinkage()) Out << "external "; - + PrintLinkage(GV->getLinkage(), Out); PrintVisibility(GV->getVisibility(), Out); @@ -1480,7 +1480,7 @@ void AssemblyWriter::printGlobal(const GlobalVariable *GV) { Out << ' '; writeOperand(GV->getInitializer(), false); } - + if (GV->hasSection()) Out << ", section \"" << GV->getSection() << '"'; if (GV->getAlignment()) @@ -1503,9 +1503,9 @@ void AssemblyWriter::printAlias(const GlobalAlias *GA) { Out << "alias "; PrintLinkage(GA->getLinkage(), Out); - + const Constant *Aliasee = GA->getAliasee(); - + if (const GlobalVariable *GV = dyn_cast(Aliasee)) { TypePrinter.print(GV->getType(), Out); Out << ' '; @@ -1527,7 +1527,7 @@ void AssemblyWriter::printAlias(const GlobalAlias *GA) { "Unsupported aliasee"); writeOperand(CE, false); } - + printInfoComment(*GA); Out << '\n'; } @@ -1536,13 +1536,13 @@ void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) { // Emit all numbered types. for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { Out << '%' << i << " = type "; - + // Make sure we print out at least one level of the type structure, so // that we do not get %2 = type %2 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out); Out << '\n'; } - + // Print the named types. for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end(); TI != TE; ++TI) { @@ -1568,7 +1568,7 @@ void AssemblyWriter::printFunction(const Function *F) { Out << "declare "; else Out << "define "; - + PrintLinkage(F->getLinkage(), Out); PrintVisibility(F->getVisibility(), Out); @@ -1613,10 +1613,10 @@ void AssemblyWriter::printFunction(const Function *F) { for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { // Insert commas as we go... the first arg doesn't get a comma if (i) Out << ", "; - + // Output type... TypePrinter.print(FT->getParamType(i), Out); - + Attributes ArgAttrs = Attrs.getParamAttributes(i+1); if (ArgAttrs != Attribute::None) Out << ' ' << Attribute::getAsString(ArgAttrs); @@ -1656,7 +1656,7 @@ void AssemblyWriter::printFunction(const Function *F) { /// printArgument - This member is called for every argument that is passed into /// the function. Simply print it out /// -void AssemblyWriter::printArgument(const Argument *Arg, +void AssemblyWriter::printArgument(const Argument *Arg, Attributes Attrs) { // Output type... TypePrinter.print(Arg->getType(), Out); @@ -1696,7 +1696,7 @@ void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { Out.PadToColumn(50); Out << ";"; pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB); - + if (PI == PE) { Out << " No predecessors!"; } else { @@ -1982,7 +1982,7 @@ void AssemblyWriter::printInstruction(const Instruction &I) { writeOperand(I.getOperand(i), PrintAllTypes); } } - + // Print post operand alignment for load/store if (isa(I) && cast(I).getAlignment()) { Out << ", align " << cast(I).getAlignment(); @@ -2060,7 +2060,7 @@ void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { MDNode *MD = dyn_cast_or_null(N->getElement(i)); if (MD) OS << '!' << SlotTable.getMetadataSlot(MD); - else + else OS << "null"; } OS << "}\n"; diff --git a/lib/VMCore/Instruction.cpp b/lib/VMCore/Instruction.cpp index efa80d16ef9..35fb47a5ffb 100644 --- a/lib/VMCore/Instruction.cpp +++ b/lib/VMCore/Instruction.cpp @@ -292,11 +292,11 @@ bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const { return true; continue; } - + if (PN->getIncomingBlock(UI) != BB) return true; } - return false; + return false; } /// mayReadFromMemory - Return true if this instruction may read memory. @@ -380,8 +380,8 @@ bool Instruction::isCommutative(unsigned op) { static bool isMalloc(const Value* I) { const CallInst *CI = dyn_cast(I); if (!CI) { - const BitCastInst *BCI = dyn_cast(I); - if (!BCI) return false; + const BitCastInst *BCI = dyn_cast(I); + if (!BCI) return false; CI = dyn_cast(BCI->getOperand(0)); }